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 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 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-Structures :

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 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 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 : Understand By Examples :

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 : Call by Reference : Understand By Examples :

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 But 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


The entire article is well narrated in the below Video :

1/12/2022

Nested Data Structure in PERL


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 :

1/11/2022

Data Structure in PERL : Associative Array and Reference


In previous article we have discussed about the Array . Now , in this article we will cover the Linked List or the HASH-Table i.e Associative Array in PERL.


Associative Array / Hash in PERL :

  • An associative array(hash) is an array of scalar values associated with the subscripts/index that are not 0, 1, 2, 3 ... 
  • Rather subscripts/index are any scalar values with no particular order. 
  • These subscripts are called "keys". Corresponding array elements are called "values".
  • A "value" is mapped to its corresponding "key".
  • Thus a hash is a table of uniquely mapped key-value pairs. Generically it is called as hash table or hash.
  • Hash variables always start with % (percent) symbol.

Creation of an Associative Array  :

The HASH can be created in below ways :-

1. Entire hash variables(key&value) are referenced using the “%” ;

my %hash = ("name", "Billy",

"age", 21 ,

"occupation", "student"

);

my %hash = ("name" => "Billy",

"age" => 21,

"occupation" => "student"

);

2. Individual hash variables (scalars) are mapped using $name{key} = value ;

$hash{"name"}= "Billy" ; # note we are using { } and not using  [ ]

$hash{"age"} = 21;

$hash{"occupation"} = "student";


Accessing Hash Key/Value after Hash Creation :

The key-value pair can be access in below ways :-

1. When you know the key ;

print "$hash{"name"}"; #prints Billy

print "$hash{"age"}"; #prints 21;

print "$hash{"occupation"}"; # Prints student


2. When you do not know the keys;

my @arr = keys(%hash); #returns list of keys

foreach my $key (@arr) {

     print “Key = $key has Value = $hash{$key}\n”;

}

3. Get the Key Value pair at once using each function ;

while (($key,$value) = each(%hash)) {

   print “Key = $key has Value = $value \n”;

}

Associative Array / Hash Functions :

There are few functions are there to operate exclusively on HASH :

  • keys - returns a list of the keys
  • my @keyArr = keys(%hash);
  • values - returns a list of the values
  • my @valArr = values(%hash);
  • each - returns a (key, value) pair in sequence
  • delete - removes a key-value pair from a hash
  • delete $hash{"key1"} ; 
  • %b = %a; # copies hash into other
  • %a = reverse %b; # swap keys and values, values should be unique


Array and Hash : Mutual Conversions :

We can mutually convert the array and hash in to each other as :-

  • my @arr = %hash; # converts a hash into a array
  • # Not necessarily in that order, but always with keys
  • # and values paired adjacently
  • my %newHash = @arr; # converts array back to a hash
  • my %arr = ("key1", val1 ,"key2", val1, "key3", val3); # creates a hash from list
  • my @arr{"key1","key2","key3"} = (val1,val2,val3); # same thing


References in PERL :

  • PERL allows you have "hard" references to any piece of data or code.
  • Any scalar may hold a hard reference. 
  • Arrays and hashes contain scalars.
  • Hence one can now easily build nested data structures as :
  • arrays of arrays, arrays of hashes , hashes of arrays, arrays of hashes of functions, and many other combinations..…
  • [ ITEMS ] makes a new, anonymous array, and returns a reference to that array.
  • { ITEMS } makes a new, anonymous hash, and returns a reference to that hash.


Backslash Operator & ref() function  : 

By using the backslash operator on a variable, subroutine, or value typically creates another reference to a variable.

Backslash Operator (\) is similar to the address-of-operator(&) in C.

$scalarref = \$foo; #reference to a scalar 

$arrayref  = \@ARGV; #reference to an Array

$hashref   = \%ENV; #reference to a Hash

$constref = \186_282.42; #reference to a constant

$coderef   = \&handler; #reference to a piece of code

$objRef = new Student("Name", "Surname" , "Roll"); #reference to a object 

There is a inbuilt function ref() which will check & return the reference type 

Usage : ref($refVar) #$refVar is the reference variable in concern

Reference Example 

Through this example , we will demonstrate the use of ref() function and see its output in various cases :

 

Upon execution this code gives the below output which is self explanatory :


With the below code-example we do the Anonymous Referencing & De-Referencing :

Request you to run this code at your end .

De-Referencing : Arrow Notation :

# Accessing A Value 

print "$ArrayRef->[0]";

print "$HashRef->{"KEY"}";

# Assigning A Value

$ArrayRef->[0] = "January";   # Array element

$HashRef->{"KEY"} = "VALUE";  # Hash element

Unnamed Associative Array/Hash :

With the below code example we will create and access unnamed hash :

Upon execution the code gives the below output :


The entire article is well narrated in the below video :