Showing posts with label PERL in VLSI. Show all posts
Showing posts with label PERL in VLSI. Show all posts

1/27/2022

Object Oriented PERL Programming



In this article, we explore Object-Oriented Programming (OOP) in Perl, starting with the concepts of Packages and Modules for organizing and reusing code. We explain the syntax for creating custom Perl modules and introduce OOP principles, illustrating their real-life applications and benefits for code organization, maintainability, and reuse. Key OOP elements in Perl—objects, classes, blessing, constructors, destructors, methods, attributes, and inheritance—are demonstrated through coding examples. We also showcase the Moose.pm module, highlighting its expressive syntax and powerful features to simplify OOP development. Practical examples guide viewers in creating classes, objects, and writing modular, maintainable Perl code.

In this article we will cover the Object Oriented PERL through the below mentioned subtopics :

  • Package & Module in PERL
  • Package/Module Example
  • Object Oriented Programming (OOP) Concept
  • When to use OOP 
  • Object/Class/Blessing/Constructor/Destructor/Methods/Inheritance
  • Coding Example : Class & Object Creation in PERL
  • Coding Example : Inheritance Class & Object Creation in PERL 
  • Coding Example : Class & Object Creation in PERL using Moose.pm

Perl Package & Module :

  • A namespace stores names of variables, subroutines, filehandles, and formats belonging to its scope. 
  • Each namespace has its own symbol table, which is basically a hash table.
  • Perl Namespaces are called "packages".
  • The default namespace for any PERL program is main.
  • Package declaration tells the compiler which namespace to prefix to our variables.
  • A module is a package defined in a file whose name is the same as the package.
  • All Perl modules are contained in global @INC array, which contains a list of library directories/paths.
  • A module/package can be included in your program with use or require functions of PERL.

A Perl Module :

  • A module is just a set of related functions in a library file! 
  • Perl package with the same name as the file (FileName=SomeModule.pm). 
  • File extension is .pm and NOT .pl

The module definition starts with : 

package SomeModule;  

use warning;

use strict;

# Code of this module goes here

# Subroutines 

# end of this module is declared by

1;  # don't forget to return a true value from the file


Usage of Custom Perl Module :

Keep the PM file in your current working directory

For any other directory , specify it in your .cshrc file & source it:

setenv PERL5LIB '/home/<userName>/PERL_Modules'

setenv PERLLIB '/home/<userName>/PERL_Modules'

Then use in your present myProg.pl as

use SomeModule;

or

require SomeModule;

or

require "SomeModule.pm";


Package/Module Example :

Here is how we create a PERL Module abc.pm :

And here is the example how we use it :


Object Oriented Concept :



  • Most object systems share a number of common concepts.
  • Understanding the concepts will make it much easier to read and write object-oriented code. 
  • Perl's OO system is class-based. Class-based OO is fairly common. 
  • It's used by Java, C++, C#, Python, Ruby, and many other languages. 

When to Use OOP ?

  • The system being designed is large, or is likely to become large over time.
  • The data can be put into obvious structures.
  • There is prominent of inheritance and polymorphism.
  • There is a piece of data on which many different operations are applied.
  • You may need to perform the same general operations on related types of data, but with slight variations depending on the specific type of data the operations are applied to.
  • Chances are there that you may add new data types later.
  • The implementation of individual components of the system is likely to change over time.
  • The system design is already object-oriented.
  • Large numbers of other programmers from multi site will be using your code modules.

Objects :

  • An object is a data structure that bundles together data and subroutines which operate on that data.
  • An object's data is called attributes, and its subroutines are called methods.
  • An object can be thought of as a noun (a person, a web service, a computer).
  • An object represents a single discrete thing.
  • For example, an object might represent a file. 
  • The attributes for a file object might include its path, content, and last modification time. 

Class :

  • A class defines the behavior of a category of objects.
  • A class is a name for a category and a class also defines the behavior of objects in that category.
  • A specific object is often referred to as an instance of a class.

In Perl, any package can be a class.

The difference between a package which is a class and one which isn't is based on how the package is used. Here's our "class declaration" for the File package: 

Blessing :

Most Perl objects are hashes, but an object can be an instance of any Perl data type (scalar, array, etc.). Turning a plain data structure into an object is done by blessing that data structure using Perl's bless function.

We sometimes say that an object has been "blessed into a class".

Constructor :

A constructor creates a new object belonging to a class. In Perl, a class's constructor is just another method, unlike some other languages, which provide syntax for constructors. Most Perl classes use new as the name for their constructor:

my $file = File→new(...);

Methods :

Method is a subroutine that operates on an object. 

In Perl, methods are simply subroutines that is defined inside a class's package. 

Methods are always written to receive the object as their first argument.

Attributes :

Each class can define its attributes. When we instantiate an object, we assign values to those attributes. For example, every File object has a path. Attributes are sometimes called properties.

Inheritance : 

Inheritance lets you create a specialized version of an existing class. Inheritance lets the new class reuse the methods and attributes of another class.

For example, we could create an File::MP3 class which inherits from File. An File::MP3 is-a more specific type of File. All mp3 files are files, but not all files are mp3 files.

We often refer to inheritance relationships as parent-child or super-class/subclass relationships. Sometimes we say that the child has an is-a relationship with its parent class.

File is a super-class of File::MP3, and File::MP3 is a subclass of File.

package File::MP3;

use parent 'File';

Overriding :

  • Overriding methods and method resolution
  • Inheritance allows two class to share code. By default, every method in the parent class is also available in the child. 
  • The child can explicitly override a parent's method to provide its own implementation. 

Object Oriented PERL by Example :


So far we have walked through the theories , now we will do the object oriented programming using PERL .
In the below example we create the class "Student" . The "new" is the constructor and "DESTROY" is the destructor of the class.
We have three methods : setName , setSurname and setRoll to assign Name, Surname and Roll-No to each student.
The method "display" is to printout the rerecords of a student . 
Here goes the code :

In the below code we create two student objects from the above class :

Once we execute the code we get the below output :




Inheritance Example :


In the next code we will exemplify the Inheritance. Here the derived class is "intern" whose parent class is "student".

Here goes the inheritance class :

Now we create the objects of this class in the below example :
Once we execute the code we get the below output :




Creating Class Using Moose Package :


We have a PERL package , Moose.pm which is available from CPAN Network . We can use the module and create PERL objects in the easy way. Using moose we can declare the class i the below way.

 

And we can use it to create objects in the below fashion :


Once we execute the codes we get the below output :




The Moose.pm can be Installed in your Ubuntu System Easily . See the below Video :



The Entire Article is Well Narrated in the below video :




Courtesy : Image by Jae Rue from Pixabay 



1/20/2022

Regular Expressions (RegEx) in PERL


In this article, we dive into the essentials of Regular Expressions (RegEx) in PERL, exploring real-world applications in VLSI with two examples. We cover string operations, introduce RegEx fundamentals, and explain the role of meta-characters and meta-symbols. Key topics include pattern matching with five examples, using non-default delimiters, extracting matched groups, and applying the split function with RegEx. We also highlight similarities between PERL and SED in search-and-replace functionality, showcasing RegEx's versatility and power.


Here we will learn the Regular Expression or RegEx in PERL in the below sequence :

  • Application of RegEx in VLSI
  • String Operation in PERL
  • Meta-Character & Meta-Symbols in RegEx
  • Pattern Matching through RegEx in PERL
  • Non-Default Delimiters
  • Matched Group & It’s Extraction
  • Split Function & RegEx in PERL
  • Search & Replace in PERL similar to SED

RegEx & Parsing of Files in EDA Automation :

The Regular Expression (RegEx) is the most important feature of PERL . RegEx has its importance and influence over the data processing/post-processing and EDA Automation in managing VLSI Tool Run. PERL and RegEx together are used to maintain the right sequence of VLSI Tool run in the RTL ot GDSII Flow. This section is very important to you if you are going for any VLSI Job interview which have PERL in the Job Description.

We will explain further through the below info-graphics :




Parsing of the Tool Output File :

When we run a tool in VLSI , we generally get a output file with lots of text data in it , as shown in the left-most block of the above image. Generally these output file may contain resistor, capacitor, coupling-capacitor, nets and lots of other important details specific to the design-construction.  The output may vary at every design sub-stage. At the same design sub-stage the output file will vary in internal formatting and/or sequencing from one tool to another tool. Now there may be 1000-10000 entries with specific set of data as mentioned above. In addition these files may contain several error/warning messages and comments. These are very difficult to process by hand. Hence the PERL File I/O and RegEx are used together to parse the data and filter-out the required fields that you need.

Storing the parsed and filtered Data in the Data-Structure:

The file is processed line by line through File I/O. Then RegEx matching is done . The filtered the data is stored in the convenient PERL Data Structure. These data structure may be a simple HASH or Array. In case of complex data organisation , you may have to use a Nested Data Structure such as Array of Hash or Hash of Array. This is shown in the middle block of the above info-graphics. Remember after the data population is done , you must check the sanctity of the data through the Data::Dumper module. 

Making A Hard Copy of the Parsed Data :

After the Sanctity is checked of the parsed data, It is a wise option to dump the data in to a file in the disk. Generally this output files are either CSV or EXCEL file. This is shown in the third block of the above info-graphics. Although , in some cases these might XML file too. The CSV or the Excel file later can be opened and analysed through MS-Excel or Open-Office/Libre-Office Spreadsheet Applications. In these post processing, you may use sorting , using-threshold , custom equations etc in the spreadsheet . Also you may plot the data in the spread sheet in various forms ans shapes.

Bench-marking of  Tools in EDA Automation :

Bench-marking of Tool-A Vs Tool-B is done very frequently in VLSI Companies. This is due to be over sanguine about the outcome of the two tool runs.  

In MNCs similar tool from three major EDA Vendors are used in the design till sign-off. When any new tool is introduced by any of the Tool Vendor , it  also get bench-marked by the design house during its trial period.
In general reported error/warning/violations are filtered from the benchmark and analysed deeply. The odd-man-out are noted down from the bench-mark output. These are good to catch at the beginning.
When all the errors/warnings/violations are mapped among the multiple tools under benchmark exercise and there are no odd-man-out are left-out , the designers feel relieved and start their debug process.



In the above picture the two output files from Tool-A and Tool-B are populated into PERL Hash using the RegEx matching. 
Now we can iterate using the loops in PERL over the two Hashes side by side and match the Current/Voltage/Slew etc of any particular resistor between the output of  two tools.
Then we can save the compared output in disk using File I/O routines in TCL.

Strings in PERL :

  • Strings aren’t technically a separate data type i.e. they can be stored in scalars.
  • Single-quotes are the “standard” delimiters for strings : everything inside the single quotes is taken literally. 
  • Double-quoted strings are “interpolated” : any variable names found inside the string will be replaced by their value. 
  • To compare two strings, we use the string comparison operators: eq (equal), ne (not equal), lt (less than), gt (greater than), le (less or equal), and ge (greater or equal).

Examples of Strings in PERL  : 

my $animal = "Camel"; # pure string
my $sign = "I love $animal"; # string with interpolation
my $cost = 'It costs $100'; # string without interpolation
my $cwd = `pwd`; # string output from a command

Regular Expression (RegEx) in PERL  :

  • A regular expression is simply a pattern which implicitly generates a family of strings, expressed in a special notation. 
  • a*z  - This pattern generates possible family of strings : ‘a’, ‘az’, ‘aa’, ‘aaz’, ‘aaaaaaaaz’, etc. 
  • The matching operator, //, returns true if the string it is bound to matches the regular expression it contains.
  • There are two pattern-matching operators, which by default operate on the default scalar, $_ 
  • These are :
  • The matching operator, /Pattern/, returns true if the string matches the regular expression it contains.
  • The substitution operator, s/Pattern/Replacement/, replaces the Pattern with Replacement if match is found.  
  • Most characters in a regular expression simply represent themselves.
  • Except : \ | ( ) [ { ^ $ * + ? . 
  • These are called meta-characters and have special meanings. 

Meta-Characters And Their Meaning in PERL-RegEx :

^ Matches the beginning of a string
$ Matches the end of a string
. Matches any single character
* Matches any count (0-n) of the previous character
+ Matches any count, but at least 1 of the previous character
[...] Matches any character of a set of characters
[^...] Matches any character *NOT* a member of the set of characters following the ^.
(...) Groups a set of characters into a subSpec.
{m} Exactly m times
{m,} At least m times
{m,n} At least m but not more than n times


Meta-Symbols And Their Meaning in PERL-RegEx :

\d matches a digit, not just [0-9] but also digits from non-roman scripts
\s matches a whitespace character, the set [\ \t\r\n\f] and others
\w matches a word character (alphanumeric or '_'), not just [0-9a-zA-Z_] but also digits and characters from non-roman scripts
\D is a negated \d; it represents any other character than a digit, or [^\d]
\S is a negated \s; it represents any non-white-space character [^\s]
\W is a negated \w; it represents any non-word character [^\w]
The period '.' matches any character but "\n" (unless the modifier /s is in effect, as explained below).
\N, like the period, matches any character but "\n", but it does so regardless of whether the modifier /s is in effect.
Pattern Matching in PERL RegEx : Examples :
‘abcdef’ –Matches ‘abcdef’.
‘a*b’ –Matches zero or more ‘a’s followed by a single ‘b’. For example, ‘b’ or ‘aaaaab’.
‘a?b’ –Matches ‘b’ or ‘ab’.
‘a+b+’ –Matches one or more ‘a’s followed by one or more ‘b’s: ‘ab’ is the shortest  possible match, but other examples are ‘aaaab’ or ‘abbbbb’ or ‘aaaaaabbbbbbb’.
‘.*’ or ‘.+’ –These two both match all the characters in a string; however, the first matches every string (including the empty string), while the second matches only strings containing at least one character.
‘[a-zA-Z0-9]’ –This matches any ASCII letters or digits.

Examples and More Examples .... :
So far we have discussed over importance , rules and regulation of RegEx in PERL. Now let use dive into some of the examples to understand it.
Here is an examples of the a positive match case of PERL RegEx :


Here goes an example of the negative match case of PERL RegEx :



The below example tells you what to expect and what not to expect from PERL RegEx :

The below example tells you what is obvious and what not in PERL RegEx :

The below example tells you to how to combine alpha-numeric combinations in PERL RegEx :



Non-Default Delimiters :

The // default delimiters for a match can be changed to arbitrary delimiters by putting an 'm' out front:
"Hello World" =~ m{World};   # matches, note the matching '{}'
"/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
                             # '/' becomes an ordinary char

"Hello World" =~ m!World!;   # matches, delimited by '!'


Extracting Match Group :

  • The grouping meta-characters ()  allow the extraction of the parts of a string that matched. 
  • For each grouping, the part that matched inside goes into the special variables $1, $2, etc. 
  • They can be used just as ordinary variables, see the below code example :


The below example shows the group matching :

RegEx Split Function in PERL :

  • The split() function is another place where a RegEx is used.
  • It returns a list of values that don't match a given regex in a search string.
  • The /Pattrn/ works as a delimiter to split the string into smaller sub-string
  • These sub-strings are returned in form of an array.
Here is an short and sweet example of  Split Function :



RegEx Search and Replace in PERL :

  • Search and replace is performed using s/regex/replacement/modifiers.

  • The replacement is a Perl double-quoted string that replaces in the string whatever is matched with the regex. 
  • The operator =~ is also used here to associate a string with s///. 
  • If matching against $_, the $_ =~ can be dropped.
  • If there is a match, s/// returns the number of substitutions made;
  • Otherwise it returns false. 
The below example shows the various cases of search and replace :


The entire article is well narrated in the below video :


 

Courtesy : Image by Jae Rue from Pixabay 



1/13/2022

File I/O in PERL



In this article, we cover essential topics in PERL related to file I/O, globbing, and logging. We start with the basics of file operations—read, write, and append modes—and introduce a shorthand for the open command for efficiency. Key highlights include reading files, testing files with if conditions, and advanced techniques for memory-efficient file reading, including loading files into arrays. We also explain writing to files, managing STDIN, STDOUT, and STDERR streams, and creating log files for tracking script execution. Finally, we explore globbing, showcasing how to perform Unix-style file operations seamlessly in PERL.

In this Article we will learn the FILE IO in PERL in the sequence :

  • File Input/Output in PERL
  • Shorthand file open command
  • Reading from a File : Two Ways
  • Reading a file into an Array
  • Writing into a File
  • Dealing with STD I/O 
  • Overall Log Files for a PERL script
  • Glob-ing  & Unix Style File I/O in PERL

File Input/Output in PERL:

A FILEHANDLE is the name for an I / O connection between your Perl process and the I / O device.

Filehandles are ALL UPPERCASE to avoid possible collisions with present or future reserved words.

A file can be opened using  : open ( filehandle, mode, filename );

A file can be closed using   :  close function as : close ( filehandle );

Open returns nonzero on success, the undefined value otherwise. 

If the open involved a pipe, the return value happens to be the PID of the sub-process.

When opening fails, it's never a good idea to continue !

Hence we use perlfunction die to terminate the program if the file open fails.

File Handle Modes in PERL :

The Various MODE strings in "open( filehandle, mode, filename )" are tabulated below with their respective meaning :


Some Short-hands for Open Command in PERL :

Here are some pre-constructed open commands for you with their meanings in the RHS :

Reading From a File in PERL : By Example :
Testing the File On Disk Before Opening It :

Here goes a basic prototype of file open code sequence in PERL :

The above code is self-explanatory and request you to do experiments with this at your end.

Several File Test operators can be used along with IF Condition before you open a file in/from the disk. These test cards help you to make fail-safe operation in file operation min PERL . Here is the exhaustive list :


Reading From A File : Example 

Here is typical prototype of a file open routine in PERL :

Reading a File Directly into An Array :
Writing into a File in Disk :
Opening STD I/O Through PERL File Handle :

We can directly open a file into an Array where each element of the Array is Each line of the file. Here is the short and sweet code for the same :

Here goes a short and sweet example of the write routine in PERL : 

Standard handles: STDIN, STDOUT, STDERR  are opened by default :

print STDOUT "Enter a number: "; # ask for a number

my $number = <STDIN>; # input the number

print STDOUT "The number is $number\n"; # print the number

print STDERR "An error has occured !\n"; # print the error

EDA Automation : Creating Overall Log File for YOUR OWN PERL SCRIPT :

#It is necessary to create a overall LOG file of your script

#That can capture screen dump of messages

#That can capture screen dump of all the errors and warning.

use File::Tee qw(tee);

tee(STDOUT, '>', 'myPerlScript.log');

tee(STDERR, '>', 'myPerlScript.error.warn.log');

EDA Automation : Glob-ing in PERL :

Definition: The expansion of filename argument patterns into a list of matching filenames.

Here is the code snippet to perform glob-ing in PERL :

Unix Style File Operation in PERL :

Here are some PERL routines which can do file operations in UNIX/LINUX style which sitting inside the PERL code itself :

unlink("myfile.dat"); # removes myfile.dat

unlink <*.o>; # same as “rm *.o” in Unix.

rename("oldname", "newName"); # same as “mv oldname newName” in Unix. returns false if couldn’t rename

mkdir("datafiles", 0777) or warn "Cannot make datafiles directory: $!"; # create datafiles with world r/w/x permissions

rmdir("datafiles"); # deletes datafiles directory if it’s empty

chmod(0777, "myProg.pl"); # gives world r/w/x permissions to myProg.pl file

The Entire article is well narrated in the below video :



Courtesy : Image by Jae Rue from Pixabay 



Functions / Subroutines in PERL



In this article, we explored key concepts in PERL programming. We began with User-Defined Functions, highlighting their role in creating reusable and efficient code. Next, we covered Subroutine Declaration and Definition, focusing on syntax and rules, followed by a discussion on Passing and Receiving Arguments, showcasing effective data handling in subroutines. We demonstrated Call by Value and Call by Reference, explaining their differences with practical examples. The flexibility of Variable Arguments and the utility of Fixed Arguments with Multiple Return Values were also emphasized. Additionally, we examined the use of the "my" keyword for creating private variables and the "local" keyword for temporary modifications of global variables. Finally, we introduced PERL Built-in Functions, offering a powerful toolkit for streamlined programming.


In this article we will learn what is a PERL Subroutine through the below sections :

  •  Subroutines / Functions in PERL
  •  Declaration & Definition of Subroutines
  •  Passing & Receiving Arguments
  •  Call by Value
  •  Call by Reference 
  • Variable & Fixed Arguments 
  • Private & Temporary Variables
  • Built In Functions in PERL.


Subroutines/Functions in PERL :

  • Like many programming languages, Perl provides user-defined subroutines (a.k.a function). 
  • These may be located anywhere in the main program.
  • Subroutines defined in separate files can be loaded via the do, require, or use keywords.
  • A function/subroutine can be called by reference using a CODE reference variable.
  • Placement may be before or after main program text (after is preferred).
  • No type associated with function name.
  • No argument list given with function definition.
  • No local subroutines. If there are two with the same name then the 1st is overwritten.
  • In general a function without an explicit return statement is called a subroutine.
  • There's really no difference from Perl's perspective.
  • Return statement - very similar to C++ .
  • Type of data returned is relaxed, as function has no type associated.
  • May return a scalar or a list.

Declaration & Definition of Subroutine in PERL :

The subroutine Declaration is done at the  beginning of the code as :


At later part of the code i.e. after the MAIN section of the code , the explicit/inflated  definition is described :

Passing and Receiving Arguments :

Arguments are passed in form of a list/array with parentheses.

Example:  my $sum = add(2,7);

Inside the body of the function , arguments are received via a special variable name: the @_ array

$_[0] has the first argument, $_[1] has the second,  and so on .....

$#_ has the subscript of the last argument

undef is given to values beyond the end of the @_ array.

Subroutines : Call by Value 

Here is a example of calling a void function/subroutine :

hello(); # called as a void function

We define two variable & swap their values through a subroutine. 

my $x = "first";

my $y = "last";

swap($x, $y); # $x will be "last" and $y will be "first"

We have not shown the internal code of swap function/subroutine.

In the below example we get the max out of the to arguments in the scalar in the LHS.

my $a = max(2,3); # a will get 3

We can use a function/subroutine directly inside a print statement as :

print max(2,3) + max(4,5); # it prints 8

Subroutines : all by Reference 

We can create a Anonymous Function which we can later call by reference. Also once we write a regular function , later we call it by reference. Both the form are shown below through a easy code.

Which upon execution gives the below output :


By looking at the output you can easily understand that both call-by-reference happen successfully.

Subroutine with Variable Arguments :

So far we have seen the functions/subroutines with fixed number of arguments in this articles.

In the below code example we have defined a subroutine to accept any number of arguments and so the addition of all the arguments. 

Run the code at your end and see the obvious output.

Subroutine with Fixed Arguments and Multiple Return Values :

In this code-example we have modular subtraction function implemented which only outputs the numerical difference between two numbers.

Run the code at your end and see the obvious output.

Private Variables by Using “my” in Subroutine Blocks :

When we use inside a subroutine block :

my $foo;            # declare $foo lexically local

my (@wid, %get);    # declare list of variables local

my $foo = "flurp";  # declare $foo lexical, and init it

my @oof = @bar;     # declare @oof lexical, and init it

Temporary Values by “local” in Subroutines :

When we use inside a subroutine block:

local $foo;                # make $foo dynamically local

local (@wid, %get);        # make list of variables local

local $foo = "flurp";      # make $foo dynamic, and init it

local @oof = @bar;         # make @oof dynamic, and init it

local $hash{key} = "val";  # sets a local value for this hash entry

delete local $hash{key};   # delete this entry for the current block

Built In Functions in PERL :

PERL has a lot of pre-built function/subroutines and yu must not use these names for your custom subroutines. Rather feel free to use them whenever you need :

#Numeric functions

abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt, srand

#Functions for list data

grep, join, map, qw//, reverse, sort, unpack

#Functions for real @ARRAYs

each, keys, pop, push, shift, splice, unshift, values

#Functions for real %HASHes

delete, each, exists, keys, values

#Functions for filehandles, files, or directories

-X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename, rmdir, select, stat, symlink, sysopen, umask, unlink, utime

#Functions for SCALARs or strings :

chomp, chop, chr, crypt, fc, hex, index, lc, lcfirst, length, oct, ord, pack, q//, qq//, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, y///

#Regular expressions and pattern matching

m//, pos, qr//, quotemeta, s///, split, study


Watch the video The entire article is well narrated in the below Video :

Courtesy : Image by Jae Rue from Pixabay



 

1/12/2022

Nested Data Structure in PERL


In this article, we explored advanced data structures in PERL, focusing on efficient data organization. We began with Nested Arrays, showcasing how arrays within arrays enable multi-dimensional data structures. Next, we examined Nested Referenced Arrays, highlighting the power of references for creating complex structures, and discussed the Equivalence of Arrow Operator for simplified access.  We then covered Nested Hashes, where hashes contain other hashes, and Nested Referenced Hashes, demonstrating dynamic and interconnected hash structures. Our journey continued with Hybrid Data Structures, including Array of Hash, combining arrays and hashes, and Hash of Array, which stores arrays as hash values. To conclude, we emphasized the importance of the "use strict" pragma in VLSI design, ensuring robust error checking and reliable code quality in complex systems. This session provided valuable insights into PERL's capabilities for efficient and versatile data management.

In PERL the two data structure i.e Array and Hash , both can be nested. There can be simple nesting as well as complex nesting. In this article we will understand the various nesting of PERL Data Structures through various explicit code examples and outputs.


Nested Arrays in PERL :

In the below example , we have nested three anonymous array inside an Array .  One thing I will make clear that the array which stay inside the nest , always the anonymous array.

Here goes the code :

As shown in the code the array as a whole can be printed using the Dumper module or by picking the element individually as : $NestedArray[0][1] .

Upon execution of the code it gives the below output :


Nested Referenced Arrays :

This example is a bit different from the above one. Here the holding nest i.e the mother array is a referenced-array. As shown in the code the array as a whole can be printed using the Dumper module or by picking the element individually as : $refNestedArray->[0][1] .  Here you can spot the difference.

Here goes the code :

Once executed it gives the below output :


Equivalence of Arrow Notation :

The Arrow Notation, which is used to access nested data structure elements , can interchangeably be used in two ways  as shown in the table below:


In the programmer's community the Arrow Notation in R.H.S Column is more popular due to its  Easier to Read & Easier to Visually Interpret format.

You can use which ever you feel easy to remember !

Nested Hash in PERL :

In the Nested Hash , can be created in the below ways :

Each Individual elements can be accessed as print $NestedHash{flintstones}->{lead}; or the entire nest  can printed with the Dumper Module.

Nested Referenced Hash in PERL :

The Above Code will change as below if we change the nest as the Referenced Hash :

Hope you can spot the differences with the previous code !


Hybrid Nesting :  Array of Hash

We can create the nest with one data structure and content of the nest with another kind of the data structure . Here goes our first hybrid nesting :

The Nest is an Array while the eggs in the nest are hashes .

Hybrid Nesting : Hash of Array 

Here The nest is a Hash while the eggs are Array :

Recommended Further Reading : 

https://perldoc.perl.org/perldsc

https://perldoc.perl.org/perllol

https://perldoc.perl.org/perlref

https://perldoc.perl.org/perlreftut 

The entire article is discussed in the below video :

Courtesy : Image by Jae Rue from Pixabay