0% found this document useful (0 votes)
22 views

Unit 1 Notes - PERL

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Unit 1 Notes - PERL

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

What is Perl?

Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl is


a term stands for “Practical Extraction and Reporting Language” even though there is no
acronym for Perl. It was introduced by Larry Wall in 1987. Perl language was specially
designed for text editing. But now, it is widely used for a variety of purposes including
Linux system administration, network programming, web development, etc.

Let’s put it in a simple manner. While computers understand just 0’s and 1’s (binary
language/machine language/ [low-level language]), it is very difficult to program in a
binary language for us human. Perl is a programming language which uses natural
language elements, words that are used in common English language and is, therefore,
easier to understand by humans [high-level language]. Now there’s a problem; computers
cannot understand high-level languages, which we humans can easily understand. For that,
we need something which can translate the high-level language to low-level language.
Here interpreter comes to our help. The interpreter is a piece of software which converts
the program written in the high-level language to low-level language for the computer to
understand and execute the instructions written in the program. Hence, Perl is
an interpreted programming language.
Where is Perl used?
The power of Perl scripting language can be implemented in many fields. The most
popular use of Perl is in Web development., Perl is also used to automate many tasks in
the Web servers, and other administration jobs, it can automatically generate emails and
clean up systems. Perl is still used for its original purpose i.e. extracting data and
generating reports. It can produce reports on resource use and check for security issues in a
network. Due to this reason, Perl has become a popular language used in web
development, networking and bioinformatics too. Apart from all this perl can also be used
for CGI programming.
Perl can also be utilized for image creation & manipulation. Apart from that networking
via telnet, FTP, etc., Graphical User Interface creation, VLSI electronics & to create mail
filters to reduce spamming practices are some use cases of Perl.
Perl is also known for implementation of OOP(object oriented programming) practices
and supports all forms of inheritance (simple, multiple & diamond), polymorphism and
encapsulation. Perl is flexible enough to support Procedural as well as OOP practices
simultaneously. Perl also has extra modules which permit you to write or use/reuse code
written in Python, PHP, PDL, TCL, Octave, Java, C, C++, Basic, Ruby and Lua in your
Perl script. This means that you can combine Perl with these extra programming
languages rather rewriting existing code.

Applications of Perl Programming Language


Why use Perl?
It is true that there are other programming languages that can be used to do all the stuff
that has been stated above, then why should you specifically use Perl? Perl is very easy to
learn, especially if you have a background in computer programming. Perl was designed
to be easy for humans to write and understand rather than making it easy for processing by
computers. It uses regular expressions. It’s natural style of language is different from other
programming languages that use specific grammar and syntaxes; therefore, Perl is very
flexible and doesn’t impose on you any particular way of thinking out a solution or a
problem. Perl is extremely portable. It can run on any operating system that has Perl
interpreter installed, so it is platform independent. All Linux Operating Systems come
installed with Perl, so you can start Perl coding in Linux out of the box. This is unlike
Shell scripts, where the code changes with the flavor of Linux distribution being used,
making it less and less portable Small specific tasks in Perl become very easy and
quick. Throughout this Perl tutorial for beginners, you will learn how you can code small,
quick programs for specific tasks. Let’s take a simple example of the classic Hello World
program which is used to begin learning any programming language which has UNIX as
its roots:
Example: Perl hello world

#!/usr/bin/perl
print "Hello, world!";
Output:
Hello, world!
The above two lines of code will print Hello, world! Now wasn’t it too simple and quick?
Students with knowledge of C, C++ will know that it requires many more lines of code to
obtain the same output in those languages.
You might be wondering why Perl is so famous on the Web. It is simple as most of the
things that happen on the web are of TEXT and Perl is very good at text processing. If we
compare Perl with any of the languages, then Perl will be the best language which is good
in File handling, text processing, and output reporting
One of the best advantages of Perl is that it is free to use
The Perl community strongly believes that software should be freely available, freely
modifiable and freely distributable. Several volunteers from Perl community strive to
make the programming language as good as possible.
Advantages and Disadvantages of Perl
Pros: Cons:

 Compared to other Programming


languages Perl is most powerful for
text handling and Parsing
 This is an interpreted language with  There is minimal GUI support as
fast execution time as there is no need compared to other Programming
to compile a Perl script languages.
 Simple and easy to program and  You need to refer to complex library
understand. modules which are not so easy to
 It is object oriented. understand (Don’t be scared once you
 CPAN library eases Perl development know how to do the things everything
(we will learn more about this later in will be easy).
the subject).  Understanding complex Patterns
 Used in Web development for mostly requires experience.
Payment Gateways.
 Used in Automation and to test most of
the Network and Storage related stuff.
Perl Variable
Now, we’ll talk about variables. You can imagine variable like kind of container which
holds one or more values. Once defined, the name of variable remains the same, but the
value or values change over and over again.
There are 3 Types of variables:

Types of Variables in Perl


The easiest ones are scalars, and this is ours today subject
Scalar Variable
This type of variable holds a single value.
Its name begins with a dollar sign and a Perl identifier (it’s the name of our variable).

Scalar variable in Perl


Naming Convention
If you are familiar with other programming languages, then you would know that there are
certain rules about naming variables. Similarly, Perl has three rules for naming scalars.

1. All scalar names will begin with a $. It is easy is to remember to prefix every name
with $. Think of it as a $scalar.
2. Like PHP. after the first character $, which, is special in Perl, alphanumeric
characters i.e. a to z, A to Z and 0 to 9 are allowed. Underscore character is also
allowed. Use underscore to split the variable names into two words. ‘But the First
character cannot be a number’
3. Even though numbers can be part of the name, they cannot come immediately after
$. This implies that first character after $ will be either an alphabet or the
underscore. Those coming from C/C++ background should be immediately able to
recognize the similarity. Examples
Perl Example:
$var;
$Var32;
$vaRRR43;
$name_underscore_23;
These, however, are not legal scalar variable names.
mohohoh # $ character is missing
$ # must be at least one letter
$47x # second character must be a letter
$variable! # you can't have a ! in a variable name
The general rule says, when Perl has just one of something, that’s a scalar. Scalars can be
read from devices, and we can use it to our programs.
Two Types of Scalar Data Types

1. Numbers
2. Strings
Numbers:
In this type of scalar data we could specify:

 integers, simply it’s whole numbers, like 2, 0, 534


 floating-point numbers, it’s real numbers, like 3.14, 6.74, 0.333

Notice: In general, Perl interpreter sees integers like floating points numbers. For example,
if you write 2 in your programs, Perl will see it like 2.0000
Integer literals:
It consists of one or more digits, optionally preceded by a plus or minus and containing
underscores.
Perl Examples:
0;
-2542;
4865415484645 #this also can be written with underscores (for clarity) :
4_865_415_484_645
As you can see- it’s nothing special. But believe me, this is the most common type of
scalars. They’re everywhere.
Floating-point literals:
It consists of digits, optionally minus, decimal point and exponent.
Perl Examples:
3.14;
255.000;
3.6e20; # it's 3.6 times 10 to the 20th
-3.6e20; # same as above, but negative
-3.6e-20; #it's negative 3.6 times 10 to the -20th
-3.6E-20; #we also can use E – this means the same the lowercase
version -3.6e-20

Octal, Hexadecimal and Binary representation:


It’s alternative to the decimal system. Allow me to show you Octal, Hexadecimal and
Binary representation. A short table presents all important information about this weird
styles:
Representation Base Proceeded by
Octal 8 0 (zero)
Hexadecimal 16 0x
Binary 2 0b
Perl Examples:
255; # 255 in decimal notation
0377; # 255 in octal notation
0xff; # 255 in hexadecimal notation
0b11111111; # 255 in binary notation
All of these values for Perl means the same. Perl doesn’t store the values in the same
format. It will internally convert these hexadecimal, binary, octal to decimal values.
The assignment is the most common operation on a scalar, and it’s very simple. Perl uses
for that equal sign. It takes a value of the expression from the right side and puts this value
to our variable.
Let’s take a look to examples:
$size=15; # give $size value of 15
$y = -7.78; # give $y value of -7.78
What’s more you can put in variable not only a number, but also an expression.
$z = 6 + 12 # give $z value of 18
Strings
Strings: It’s also very simple type of scalar.
The maximum length of a string in Perl depends upon the amount of memory the
computer has. There is no limit to the size of the string, any amount of characters,
symbols, or words can make up your strings. The shortest string has no characters. The
longest can fill all of the system memory. Perl programs can be written entirely in 7-bit
ASCII character set. Perl also permits you to add any 8-bit or 16-bit character set aka. non-
ASCII characters within string literals. Perl has also added support for Unicode UTF-8.

Like numbers there are two different types of strings:

 Single quotes string literals


 Double quotes string literals
Single-quoted string literals
Single quotation marks are used to enclose data you want to be taken literally. A short
example and everything should be clear:
Perl Examples:
#!/usr/bin/perl
$num = 7;
$txt = 'it is $num';
print $txt;
Output:
it is $num
Here due to single quotes value of $num in not taken and the literal characters ‘$’,’n’, ‘u’
& ‘m’ are added to the value of $txt
Double-quoted string literals
Double quotation marks are used to enclose data that needs to be interpolated before
processing. That means that escaped characters and variables aren’t simply literally
inserted into later operations, but are evaluated on the spot. Escape characters can be used
to insert newlines, tabs, etc.
Perl Examples:
$num = 7;
$txt = "it is $num";
print $txt;
Output:
it is 7
Here due to double quotes value of $num is taken added to the value of $txt
Double-quotes interpolate scalar and array variables, but not hashes. On the other hand,
you can use double-quotes to interpolate slices of both arrays and hashes.
Mysterious \n
Consider the following program
Perl Examples:
print "hello \n";
Output:
hello
Perl does not display just ‘hello\n’, but only ‘hello’. Why? Because ‘\n’ is a special sign
and means that you want to go to a new line while displaying the text in your program.
print “hello\n new line”; Next question- are there any other special sign? Yes, they are!
But don’t worry- just a few. Check the table below
Construct Description
\n newline
\r return
\t tab
\f formfeed
\b backspace
\a bell
\e escape
\007 any octal ASCII value (here, 007 = bell)
\x7f any hex value (here, 7f = delete)
\\ backslash
\” double quote
\l lowercase next letter
\L lowercase all following letters until \E
\u uppercase next letter
\U uppercase all following letters until \E
\E Terminate \L, \U
I know, there isn’t ‘just a few’… But believe me, you must to know just
Strings Variable
It’s the same operation, which we see in numbers assignment. Perl gets our string from the
right side of the equal sign and puts this string to a variable.
Perl Examples:
$string = 'tutorial'; # give $string the eight-character string 'tutorial'
print $string;
$string = $size + 3 ; # give $string the current value of $size
plus 3
print $string;
$string = $ string * 5; # multiplied $string by 5
print $string;
Output:
tutorial315
As you can see, you can put numbers and strings in the same variables. There isn’t class of
variables.
String Concatenation (period) :
The concatenation operator “.” unites two or more strings. Remember! If the string
contains quotes, carriage returns, backslashes, all these special characters need to be
escaped with a backslash.
Perl ‘ ‘ variable Examples:
#!/usr/bin/perl
$a = "Tom is";
$b = "favorite cat";
$c = $a ." mother's ". $b;
print $c;
Output:
Tom is mother’s favorite cat
The strings
“$a”, “$b”, is concatenated & stored in “$c” using the “.” operator.
In the end…
Conversion Between Numbers and Strings:
As you know, Perl automatically converts between numbers to string as needed. How does
Perl know, what we need right now? This is simple- everything depends on the operator
(we’ll talk about operators later, now, just accept there are a lot of operators, different for
numbers and strings) If an operator expects a number, Perl will use the value as a number.
If an operator expects a string, Perl will use the value as a string. In other words- you don’t
need to worry about this kind of conversion. Short example and everything should be
clear:
Perl Examples:
$string = "43";
$number = 28;
$result = $string + $number;
print $result;
Output:
71
the value of $string is converted to an integer and added to the value of $number.
The result of the addition, 71, is assigned to $result.
Scope of a variable – Access Modifiers
We can declare a scalar in anywhere in the program. But you need to specify an access
modifier
There are 3 types of modifiers
1. my
2. local
3. our
My: Using this you can declare any variable which is specific within the block. i.e. within
the curly braces.
#!/usr/bin/perl
my $var=5;
if(1)
{
my $var_2 =$var;
}
print $var_2;
No Output
The output of the program will be nothing!
In the above example, you will see that there are two variables declared one is inside if
block ($var_2) and the other is outside the If block ($var). The variable, which is declared
outside the block will be accessible to if block but the variable which was declared inside
if block won’t be accessible to the outer program.
Local: Using this we can actually mask the same variable values to different values
without actually changing the original value of the variable, suppose we have a variable $a
for which the value is assigned 5, you can actually change the value of that variable by re-
declaring the same variable using local keyword without altering the original value of the
variable which is 5. Let’s see how this works with an example.
#!/usr/bin/perl
$var = 5;
{
local $var = 3;
print "local,\$var = $var \n";
}
print "global,\$var = $var \n";
The output of the above program will be in this manner.
local, $var = 3
global, $var = 5
This way we can change the value of the variable without affecting the original value.
Our: Once a variable is declared with access modifier “our” it can be used across the entire
package. Suppose, you have Perl module or a package test.pm which has a variable
declared with scope our. This variable can be accessed in any scripts which will use that
package.
If you are serious about programming in Perl, you should begin your program with
#!/usr/local/bin/perl
use strict;
This will help you write better and cleaner code. ‘use strict’ turns on strict pragma which
will make you declare your variables with my keyword.
This is a good programming practice
#!/usr/local/bin/perl
use strict;
$var = 10;
print "$var";
Result: Error
#!/usr/local/bin/perl
use strict;
my $var = 10;
print "$var";
Output:
10
Perl Array
What is Perl Array?
An Array is a special type of variable which stores data in the form of a list; each element
can be accessed using the index number which will be unique for each and every element.
You can store numbers, strings, floating values, etc. in your array. This looks great, So
how do we create an array in Perl? In Perl, you can define an array using ‘@’ character
followed by the name that you want to give. Let’s consider defining an array in Perl.
my @array;
This is how we define an array in Perl; you might be thinking how we need to store data in
it. There are different ways of storing data in an array. This depends on how you are going
to use it.
my @array=(a,b,c,d);
print @array;
Output:
abcd
This is an array with 4 elements in it.
The array index starts from 0 and ends to its maximum declared size, in this case, the max
index size is 3.

Perl Array Example


You can also declare an array in the above way; the only difference is, it stores data into
an array considering a white space to be the delimiter. Here, qw() means quote
word. The significance of this function is to generate a list of words. You can use the qw
in multiple ways to declare an array.
@array1=qw/a b c d/;
@array2= qw' p q r s';
@array3=qw { v x y z};
print @array1;
print @array2;
print @array3;
Output:
abcdpqrsvxyz
Suppose you want to assign a value to the 5 th element of an array, how are we going to do
that.
$array [4] =’e’;
Sequential Array
Sequential arrays are those where you store data sequentially. Suppose, you want to store
1-10 numbers or alphabets a-z in an array. Instead of typing all the letters, you can try
something like below –
@numbers= (1..10);
print @numbers; #Prints numbers from 1 to 10;
Output:
12345678910
Perl Array Size
We have an array which is already available, and you don’t know what the size of that
array is, so what is the possible way to find that.
@array= qw/a b c d e/;
print $size=scalar (@array);
Can we get the size of an array without using functions? Yes, we can.
@array= qw/a b c d e/;
print $size=scalar (@array);
print "\n";
print $size=$#array + 1; # $#array will print the Max Index of the array,
which is 5 in this case
Output:
5
5
Dynamic Array
The above method of declaring an array is called static arrays, where you know the size
of an array.
What is Dynamic Array?
Dynamic arrays are those that you declare without specifying any value on them. So when
exactly do we store values in that array? Simple, we store them during run time. Here is a
simple program for that.
We will be using some inbuilt Perl functions for doing this task.
my $string="This is a kind of dynamic array";
my @array;
@array=split('a',$string);
foreach(@array)
{
print "$_ \n”;
# This is a special variable which stores the current value.
}
Output:
This is
kind of dyn
mic
rr
y
The split function splits the content of string into an array based on the delimiter provided
to it. This function will also eliminate the delimiter from the string, in this case, it is ‘a’;
Push, Pop, shift, unshift for Perl arrays:
These functions can be used in Perl to add/delete to array elements.

 Perl Push: adds array element at the end of an existing array.


 Perl Pop: removes the last element from an array.
 Perl Shift: removes the first element from an array.
 Perl Unshift: adds an element at the beginning of an array.

Let’s see an example where we can use the below functions.


@days = ("Mon","Tue","Wed");
print "1st : @days\n";
push(@days, "Thu"); # adds one element at the end of an array
print "2nd when push : @days\n";
unshift(@days, "Fri"); # adds one element at the beginning of an
array
print "3rd when unshift : @days\n";
pop(@days);
print "4th when pop : @days\n"; # remove one element from the last
of an array.
shift(@days); # remove one element from the beginning of
an array.
print "5th when shift : @days\n";
Output:
1st : Mon Tue Wed
2nd when push : Mon Tue Wed Thu
3rd when unshift : Fri Mon Tue Wed Thu
4th when pop : Fri Mon Tue Wed
5th when shift : Mon Tue Wed
Perl Hashes
Why do we need Hash?
We already learned about scalars and arrays in previous sections.
What exactly scalars do? It only stores integers and strings.
What exactly arrays do? It is a collection of scalars, where you access each element of an
array using indices. But, is this good idea to use an array when you have hundreds and
thousands of records? We will forget which index has what value. To overcome this
situation we have something like perl hash.
What are Hashes?
A hash can also hold as many scalars as the array can hold. The only difference is we
don’t have any index rather we have keys and values. A hash can be declared, starting with
% followed by the name of the hash. Let’s see an example how we can define a Perl hash
and how we can differentiate this from array
Consider an example of three people and their ages are represented in an array.
@array=('Sainath',23,'Krishna',24,'Shruthi',25); #This is how an array looks.
print @array;
Output:
Sainath33Krishna24Shruthi25
This way it is difficult to know individual ages as we need to remember both index
locations of name and age of all the people. It may be simple when you have 3 names, but
when you have 1000 or more? You know the answer.

This we can overcome using a hash.


Hash Example:
print %hash=( 'Sainath' => 23, 'Krishna' => 24, 'Shruthi' => 25); # This is how we create a
hash.
print %hash=('Sainath',23,'Krishna',24,'Shruthi',25);# This way of assigning is called list.
Output:
Sainath33Krishna24Shruthi25Sainath33Krishna24Shruthi25
We have now declared a hash, great!! But, how do we access or print it? Each element in
hash should be accessed with its associated key for which there will be a value assigned.
So, there is a one-one mapping between each of the key and value in the hash.
In order to print the age of any person, you just need to remember the name of that person.
print $hash{'Krishna'}; # This how we should access a hash. Key enclosed within {}.
You might have wondered why I used $hash{KeyName}, remember a hash is a collection
of scalars again. So, we can use $ which represents scalar to access each hash element.
Note: Each Key in hash should be unique or else it will override your value, which was
assigned previously.
How can we assign a hash to another hash? Simple, same way as we do for
We can also print entire hash.
%hash=( 'Tom' => 23);
%newHash=%hash; # Assigning hash to a new hashprint %newHash;
print %newHash;
Output:
Tom23
Add Perl Hashes
As you can see we already have a hash %newHash, and now we need to add more entries
into it.
$newHash{'Jim'}=25;
$newHash{'John'}=26;
$newHash{'Harry'}=27;
print %newHash;
Output:
Jim25John26Harry27
Perl Delete key
You may want to delete an entry from a hash. This is how we can do that.
delete $newHash{'Jim'};#This will delete an entry from the hash.
Delete is an inbuilt function of Perl. Here, we will see an example of assigning a hash to
an array.
@array=%newHash;
print "@array";
Note: Whenever you print a hash or when you store hash into an array. The order may
always differ. It’s not the same always.
We can assign only keys or values of a hash to an array.
@arraykeys= keys(%newHash);
@arrayvalues=values(%newHash);
print "@arraykeys\n";
print "@arrayvalues\n"; # \n to print new line.
To remove all the entries in the hash, we can directly assign the hash to null.
%newHash=();# This will redefine the hash with no entries.
Perl Conditional Statements
We can use conditional Statements in Perl. So, what are conditional statements?
Conditional statements are those, where you actually check for some circumstances to be
satisfied in your code.
Think about an example, you are buying some fruits, and you don’t like the price to be
more than 100 bucks. So, the rule here is 100 bucks.
Perl supports two types of conditional statements; they are if and unless.
Perl If
If code block will be executed, when the condition is true.

my $a=5;
if($a==5)
{
print "The value is $a";
}
Output:
5
Perl If Else
This looks good. Let us think about a situation where $a is not 5.
my $a=10;
if($a==5)
{
print "The values is $a ---PASS";
}
else
{
print "The value is $a ---FAIL";
}

Output:
The value is 10 —FAIL
This way we can control only one condition at a time. Is it a limitation? No, you can also
control various conditions using if… elsif … else.

Perl Else If
my $a=5;
if($a==6)
{
print "Executed If block -- The value is $a";
}
elsif($a==5)
{
print "Executed elsif block --The value is $a";
}
else
{
print "Executed else block – The value is $a";
}
Output:
Executed elsif block –The value is 5
In the above case, the elsif block will be executed as $a is equal to 5.
There could be situations where both if and elsif code blocks will be failed. In this
scenario, the else code block will be executed. You can actually eliminate the else code
check if you don’t like to include.
Perl Nested If
In this case, you can use if code block in one more if code block.
my $a=11; #Change values to 11,2,5 and observe output
if($a<10){
print "Inside 1st if block";
if($a<5){
print "Inside 2nd if block --- The value is $a";
}
else{
print " Inside 2nd else block --- The value is $a";
}
}
else{
print "Inside 1st else block – The value is $a";
}
Output:
Inside 1st else block – The value is 11
Execute the same code by change the value of $a; you can find out the rest.

Perl Unless
You have already got an idea what if does (If the condition is true it will execute the code
block). Unless is opposite to if, unless code block will be executed if the condition is false.
my $a=5;
unless($a==5)
{
print "Inside the unless block --- The value is $a";
}
else
{
print "Inside else block--- The value is $a";
}
Output:
Inside 1st else block – The value is 5
Guess what will be the output. You are right!!!!!. The output will be the print statement of
the else block. Because of the condition in unless code block is true, remember unless
block will be executed only if the condition is false. Change the value of $a and execute
the code you will see the difference.
Perl Using if
$a= " This is Perl";
if($a eq "SASSDSS"){
print "Inside If Block";
}
else
{
print "Inside else block"
}
Output:
Inside else block
Using unless
$a= " This is Perl";
unless($a eq "SASSDSS"){
print "Inside unless Block";
}
else
{
print "Inside else block"
}
Output:
Inside unless Block
Perl Loops – Control Structures
Perl supports control structures similar to other programming languages. Perl supports four
types of control structures for, foreach, while and until. We use these statements to,
repeatedly execute some code.
For loop Perl
For code block will execute till the condition is satisfied. Let’s take an example of how to
Perl loop an array.
my @array=(1..10);
for(my $count=0;$count<10;$count++)
{
print "The array index $count value is $array[$count]";
print "\n";
}
Output:
The array index 0 value is 1
The array index 1 value is 2
The array index 2 value is 3
The array index 3 value is 4
The array index 4 value is 5
The array index 5 value is 6
The array index 6 value is 7
The array index 7 value is 8
The array index 8 value is 9
The array index 9 value is 10
Here, in for () expression, there are many statements included. There is a meaning for each
of them.
for ( initialization ; condition; incrementing)
Here is another way of using for.
for(1..10)
{
print "$_ n";
print "\n";
}
Output:
1n
2n
3n
4n
5n
6n
7n
8n
9n
10n
Perl Foreach
The for each statement can be used in the same way as for; the main difference is we don’t
have any condition check and incrementing in this.
Let’s take the same example with foreach perl.
my @array=(1..10);
foreach my $value (@array)
{
print " The value is $value\n";
}
Output:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
The value is 6
The value is 7
The value is 8
The value is 9
The value is 10
Foreach takes each element of an array and assigns that value to $var for every iteration.
We can also use $_ for the same.
my @array=(1..10);
foreach(@array)
{
print " The value is $_ \n"; # This is same as the above code.
}
Output:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
The value is 6
The value is 7
The value is 8
The value is 9
The value is 10
This looks good for accessing arrays. How about Hashes, how can we obtain hash keys
and values using foreach?
We can use foreach to access keys and values of the hash by looping it.

my %hash=( 'Tom' => 23, 'Jerry' => 24, 'Mickey' => 25);
foreach my $key (keys %hash)
{
print "$key \n";
}
Output:
Mickey
Tom
Jerry
You might be wondering, Why we used Keys in foreach(). Keys is an inbuilt function of
Perl where we can quickly access the keys of the hash. How about values? We can use
values function for accessing values of the hash.
my %hash=( 'Tom' => 23, 'Jerry' => 24, 'Mickey' => 25);
foreach my $value(values %hash) # This will push each value of the key to $value
{
print " the value is $value \n";
}
Output:
the value is 24
the value is 23
the value is 25
Perl While
The Perl While loop is a control structure, where the code block will be executed till the
condition is true.
The code block will exit only if the condition is false.
Let’s take an example for Perl While loop.

Here is a problem, which will require input from the user and will not exit until the
number provided as ‘7’.
#!/usr/bin/perl
$guru99 = 0;
$luckynum = 7;
print "Guess a Number Between 1 and 10\n";
$guru99 = <STDIN>;
while ($guru99 != $luckynum)
{
print "Guess a Number Between 1 and 10 \n ";
$guru99 = <STDIN>;
}
print "You guessed the lucky number 7"
Output:
Guess a Number Between 1 and 10
9
Guess a Number Between 1 and 10
5
Guess a Number Between 1 and 10
7
You guessed the lucky number 7
In the above example, the while condition will not be true if we enter input other than ‘7’.
If you see how while works here, the code block will execute only if the condition in a
while is true.
Perl do-while
Do while loop will execute at least once even if the condition in the while section is false.
Let’s take the same example by using do while.
$guru99 = 10;
do {
print "$guru99 \n";
$guru99--;
}
while ($guru99 >= 1);
print "Now value is less than 1";
Output:
10
9
8
7
6
5
4
3
2
1
Now value is less than 1
Perl until
Until code block is similar to unless in a conditional statement. Here, the code block will
execute only if the condition in until block is false.
Let’s take the same example which we used in case of a while.
Here is a problem, which will require input from the user and will not exit until the name
provided as other than ‘sai’.
print "Enter any name \n";
my $name=<STDIN>;
chomp($name);
until($name ne 'sai')
{
print "Enter any name \n";
$name=<STDIN>;
chomp($name);
}
Output:
Enter any name sai
Perl do-until:
Do until can be used only when we need a condition to be false, and it should be executed
at-least once.
print "Enter any name \n";
my $name=<STDIN>;
chomp($name);
do
{
print "Enter any name \n";
$name=<STDIN>;
chomp($name);
}until($name ne 'sai');
Output:
Enter any name Howard
Enter any name Sheldon
Enter any name sai
Execute while, do-while, until and do-until example codes to see the difference.
Perl Operator
What is Operator?
Operators in computer language indicate an action that can be performed on some set of
variables or values which computer can understand. Perl has incorporated most of the
Operators from C language. Perl has many operators compared with other programming
languages. Operators are categorized as Arithmetic, Logical, relational and assignment
operators.
Arithmetic Operators:
Arithmetic operators are those which can be used to perform some basic mathematic
operations. These Arithmetic operators are binary operators where we need two arguments
to perform a basic operation. We can also use unary operators for other basic operations;
you can see the difference in examples below.
Operato
Description Example
r
$x=5+6; # or
Addition operation used for adding two values or variables
+ $y=6;
holding values
$z=$x+$y;
$x=6-5; # or
Subtraction operator used for subtracting two values or
– $y=6;
variables holding values
$z=$x-$y;
$x=6*5; # or
Multiplication operator used for multiply two values or
* $y=6;
variables holding values
$z=$x*$y;
$x=36/6; # or
Division operator used for divide two values or variables
/ $y=6;
holding values
$z=$x/$y;
$x=5**5; # or
The exponential operator used for provide exponent and
$x=4;
** get the value.
$y=2;
Ex : 22 = 4, 33 = 27
$z=$x**$y;
$x=5%2; # or
Modulus operator used to get the reminder during division $x=10;
%
of two values or variables holding values $y=2;
$z=$x % $y;
$x=5;
Unary addition operator to increment value of a variable $x++;
++
by 1 Or
++$x;
$x=5;
Unary Subtraction operator to decrement value of a $x–; # post decrement

variable by 1 Or
–$x;# pre decrement
Example to complete all the above operations.
my $x=10;
my $y=2;
my $z;
$z=$x+$y;
print ("Add of $x and $y is $z \n");
$z=$x-$y;
print ("Sub of $x and $y is $z \n");
$z=$x*$y;
print ("Mul of $x and $y is $z \n");
$z=$x/$y;
print ("Div of $x and $y is $z \n");
$z=$x**$y;
print ("Exp of $x and $y is $z \n");
$z=$x%$y;
print ("Mod of $x and $y is $z \n");
Output:
Add of 10 and 2 is 12
Sub of 10 and 2 is 8
Mul of 10 and 2 is 20
Div of 10 and 2 is 5
Exp of 10 and 2 is 100
Mod of 10 and 2 is 0
Assignment Operators:
Assignment operators simply assign values to variables, but there is one more thing which
we need to remember here, assignment operators will also perform arithmetic operations
and assign the new value to the same variable on which the operation is performed.
Operator Description Example
Addition operator used for adding and assigning the value to $x=4;
+=
same variable $x+=10;
Subtraction operator used for subtracting and assigning the $x=4;
-=
value to same variable $x-=10;
Multiplication operator used for adding and assigning the $x=4;
*=
value to same variable $x*=10;
Division operator used for dividing and assigning the value $x=4;
/=
to same variable $x/=10;
Exponential operator used for getting exponent and assigning $x=4;
**=
the value to same variable $x**=10;
Modulus operator used for getting a reminder during division $x=10;
%=
and assigning the value to the same variable $x%=4;
Example to complete all the above operations.
my $x=10;
$x+=5;
print("Add = $x\n");
$x-=5;
print("Sub= $x\n");
$x*=5;
print("Mul = $x\n");
$x/=5;
print("Div = $x\n");
Output:
Add = 15
Sub= 10
Mul = 50
Div = 10
Logical and Relational Operators:
Perl uses logical operators to compare numbers and strings. Most of the time logical
operators are used in Conditional Statements.

Logical and Relational Operators in Perl


Operator Description
==or eq Operator used to check whether both variables are equal
!=Or ne Operator used to check whether both variables are not equal
Operator used to check whether
> or gt
A is greater than B
Operator used to check whether
<or lt
A is less than B
Operator used to check whether
>=or ge
A is greater than or equal to B
Operator used to check whether
<=or le
A is less than or equal to B
|| or or Operator used to check either A or B is holding value
&&or and Operator used to check both A and B is holding value
Let us take an example where we can explain all the scenarios.
my $x=5;
my $y=5;
if($x == $y){
print ("True -- equal $x and $y \n");
}
else{
print ("False -- not equal $x and $y\n");
}
$x=6;
$y=7;
if($x != $y){
print ("True -- not equal $x and $y\n");
}
else{
print ("False -- equal $x and $y\n");
}
if($y > $x){
print ("True -- $y greater than $x\n");
}
else{
print ("False -- $y greater than $x\n");
}
if($x < $y){
print ("True -- $x less than $y\n");
}
else{
print ("False -- $x less than $y\n");
}
if($x <= $y){
print ("True -- $x less than $y\n");
}
else{
print ("False -- $x less than $y\n");
}
if($y >= $x){
print ("True -- $y greater than $x\n");
}
else{
print ("False -- $y greater than $x\n");
}
Output:
True — equal 5 and 5
True — not equal 6 and 7
True — 7 greater than 6
True — 6 less than 7
True — 6 less than 7
True — 7 greater than 6
You can see examples of logical operators in later sections.
Perl Special Variables
What is Perl Special Variables?
Special variables in Perl are those who have some predefined meaning. These variables
denoted with either real Name or Punctuation symbols. We have a special variable for all
the Perl supported Variables like scalar special variables, Array special variables, hash
special variables. Most of the special variables that we use are of scalars.
When we want to use the special variable with its name, then we have to load a Perl
module ‘use English,’ to explicitly say Perl interpreter that we are going to use special
variables using its Name.
Scalar special variables
Variable Description
This is the default variable which stores the current
$_$ARG
values.
$0 or $PROGRAM_NAME Stores the file name of the Perl script.
The input record separator, this has a default value of ‘\
$/
n’ which is newline character
Holds the current line number of the file that is being
$.
read
Output field separator, this is mainly used by the
$, print() statement. By default value of this is set to 0,
we can change the value of this variable.
Output record separator, the value of this variable will
$\ be empty; we can assign any value to this, which will
be used by print() statement while printing the output.
This variable is used for output format while printing
$#
numbers.
$%$FORMAT_PAGE_NUMBER Will hold the current page number of the file read.
$=$FORMAT_LINES_PER_PAGE Will Hold the current page length of the file read.
Holds the value of the number of lines left to print
$-$FORMAT_LINES_LEFT
from the page.
Format Name: Holds the format of the currently
$~$FORMAT_NAME
selected output by default the file handle name.
Holds the value of the heading format of the file
$^$FORMAT_TOP_NAME handler, by default value will be _TOP followed by file
handle name.
The default is zero; this is used to flush the output
$|$OUTPUT_AUTOFLUSH
buffer after every write() or print().
Will hold the running process number of Perl
$$
interpreter.
Status code : Pipe and system call. The return status of
$?
the command executed.
Used in regular expressions, this will hold a string of
$&$MATCH
the last successful pattern match.
Used in regular expressions, this will hold string
$`$PREMATCH
preceded by last successful pattern match.
Used in regular expressions, this will hold a string that
$’$POSTMATCH
followed by the last successful pattern match.
Holds the string of the last bracket that is matched by
$+$LAST_PAREN_MATCH
the last pattern search.
$1, $2, $3 …. Holds the values of the pattern matched
$<digit>
in order.
$[ First index: Array, a substring.
$] A version of Perl.
The separator used for list elements, by default value is
$”
a whitespace.
$; Subscript separator used in multi-dimensional arrays
In numeric context, prints the error number. In string
$!
context, print the error.
Will hold the syntax error info, used when eval() is
$@
used.
Holds the real UID (user id) of the process running the
$<
script.
Holds the effective UID of the process running the
$>
script.
Holds the real GID (group id) of the process running
$(
the script.
Holds the effective GID of the process running the
$)
script.
$^D$DEBUGGING Holds the current value of the debugging flags.
Holds the current value of the flag when –c command
$^C
line switch is used.
Maximum system file descriptor, by default value, is
$^F
set to 2
$^I$INPLACE_EDIT Holds the value of –i command line switch.
Special Memory pool can be used when Perl script dies
$^M
with an out-off memory error.
Operating system info is stored. ‘Linux’ for Linux
$^O$OSNAME
systems, ‘mswin32’ for Windows systems.
$^T$BASETIME The time when the scripts are running in seconds.
The current value of the –w command line switch.
$^W$WARNING
Warning switch.
$ARGV Name of the current file, when <> is used.
Array Special Variables:
Variable Description
Holds a list of paths, where Perl library modules or scripts can be looked into while e
@INC current script. This @INC is used by use and require statements to look into those path
modules.
@ARGV Stores the command line arguments passed.
@_ Used in subroutines, while passing the parameters to the subroutines.
This is the array into which the input lines are stored when auto split –a (command li
@F
used).
Hash Special Variables:
Variable Description
%INC The file name will be the keys; values will be the path to those files. Used by do, use and
%ENV System environmental variables.
%SIG Signals handler.
Perl Regular Expression
What is Regular Expression?
Perl regular expression is strong enough in matching the string patterns within a
statements or group of statements. Regular expressions are mostly used in text parsing,
pattern matching and much more based on the requirement. We have certain operators,
which are specially used by regular expression pattern binding =~ and !~, These are test
and assignment operators.
Regular Expression Operators

Regular Expression Operators in Perl

 Perl Match — m//


 Perl Substitute – s///
 Perl Transliterate – tr///
Before going further, We need to know few things about regular expression; there are
certain things like Meta characters, wildcards in Perl Regex syntax.
Char Meaning
\ Special or quote
* Match 0 or more characters
+ Match 1 or more characters
? Match 0 or 1 character
| Can be used to match alternative patterns
() Used to store the pattern matched
[] Set of characters can be passed. Specifically used for numeric and alphabets.
{} Used for providing the number of time the match can be performed.
^ Start of the string
$ End of string
\w Used to match a single character or word which can be alphanumeric including “_”
\W Match anything other than alphanumeric
\s Used to match whitespaces
\S Match anything other than whitespace
\d Match numbers. Not decimal values and negative values
\D Match anything other than numbers.
\t Match tab space
\n Match newline
The above are the set of characters which can be used during pattern matching.
Let’s see few examples.
Consider a situation where user provides some input during script execution, and we want
to check whether the user entered some name as input or not. We have to write a regular
expression syntax to extract your name and print the same.
my $userinput="Guru99 Rocks";
if($userinput=~m/.*(Guru99).*/)
{
print "Found Pattern";
}
else
{
print "unable to find the pattern";
}
Output:
Found Pattern
Here, we have written the regular expression as /.*(Guru99).*/.* match all characters in a
string. A ‘.’ in perl regex match refers to any character including space.
Let us see how exactly we can construct a Regex.
Consider an example of a string of multiple words and digits and special symbols like this
“Hello everyone this is my number: +91-99298373639”;
Regex : /^\w+\s\w+\s\w+\s\w+\s\w+\s\w+\:\+\d+\-\d+/i
Word space word space word space word space word space word space special character :
space special character+digits special character –digits.
Perl Match Operators
The match operators are used to match a string within some statement or in a variable.
my $var="Hello this is perl";
if($var=~m/perl/)
{
print "true";
}
else
{
print "False";
}
Output:
true
This small code will print ‘true’, as the perl pattern matching identifies the string in a
variable. Basically, Perl searches for the text provided in // throughout the string, even if it
finds in one place it will return ‘true’. The pattern can be anywhere in the variable. We can
try replacing =~ with !~ to see the difference between those two operators.
Perl Substitution Operator
This operator can be used for searching and replacing any character with either null or
some other character.
my $a="Hello how are you";
$a=~s/hello/cello/gi;
print $a;
Output:
cello how are you
Note: We can actually use any pattern matching string as we did earlier in this substitution
operator as well. Here we used ‘gi’, g-globally, i-ignore case.
Perl Translation Operator
This is similar to Substitution, but it does not use any perl regular expressions, rather we
can directly pass the value or a word which we want to replace.
my $a="Hello how are you";
$a=~tr/hello/cello/;
print $a;
Output:
Hello cow are you
Perl File I/O
Perl was designed to manipulate files and I/O operations effectively. Perl main advantage
is in file parsing and handling the files. There are many inbuilt functions and operators
used during file handling in Perl.
Basically, file operations that are performed with Perl are done using FILEHANDLE. We
have to define this FILEHANDLE during the opening a file for either read or write.
In this Perl script tutorial, you will learn-
Perl Open file
We can open a file using open() function available in Perl.
open(FILEHANDLE, "filename or complete path of the file");
Now we have opened a file, now a question arises. Is it for reading or writing?
Perl Read file & Perl Write file
Perl has certain modes, which need to be used to read, write or append a file.
Read – open(my $fh,"<filename or complete path of the file");
Write – open(my $fh,">filename or complete path of the file");
Append – open(my $fh,">>filename or complete path of the file");
Few examples for reading a file:

Consider we have a perl file with name file.txt and has few lines of text in it. We need to
open this file and print the same.
open(FH,"<file.txt");
while(<FH>) # Looping the file contents using the FH as a filehandle.
{
print "$_";
}
close FH;
or
open(FH,"<file.txt");
my @content=<FH>; # specifying the input of the array is FH.
foreach(@content)
{
print "$_";
}
close FH;
This will print the file content on the output screen.
Now, we will write a program to create and write data to a perl file.

open(FH,">test.txt");
my $var=<>;
print FH $var;
close FH;
This will write the input provided during run-time and creates a file test.txt which will
have input.
The above way will always try to create a file named test.txt and writes the input into the
file; we will write the same to append the file.

open(FH,">>test.txt");
my $var=<>;
print FH $var;
close FH;
Modes Description
< Read
+< Reads and writes
> Creates, writes and truncates
+> Read, write, create and truncate
>> Writes, appends and creates
+>> Read, write, appends and create
Now that we have to see how to read, write and append files using basic examples.
We will see few more examples and other functions which help in understanding more
about files.
Perl Tell
This method will return the current position of FILEHANDLER in bytes if specified else it
will consider the last line as the position.
open(FH, "test.pl");
while(<FH>)
{
$a=tell FH;
print "$a";
}
Perl Seek
Seek function is similar to the fseek system call. This method is used to position the file
pointer to a specific location by specifying the bytes followed by either start of the file
pointer or end of the file pointer.
seek FH, bytes, WHENCE;
WHENCE is the position of the file pointer to start. Zero will set it from the beginning of
the file.
Example:Let input.txt has some data like “Hello this is my world.”
open FH, '+<','input.txt';
seek FH, 5, 0; # This will start reading data after 5 bytes.
$/ = undef;
$out = <FH>;
print $out;
close FH;
Output:
this is my world
Perl Unlink
Unlink is used to delete the file.
unlink("filename or complete file path");
Handling Directories:
We can also handle directories through which we can handle multiple files.
let’s see how to open a directory. We can use the opendir and readdir methods.
opendir(DIR,"C:\\Program Files\\"); #DIR is the directory handler.

while(readdir(DIR)) # loop through the output of readdir to print the directory contents.
{
print "$_\n";
}
closedir(DIR); #used to close the directory handler.
or
opendir(DIR,"C:\\Program Files\\");
@content=readdir(DIR);
foreach(@content)
{
print "$_\n";
}
closedir(DIR);
This will print all the available files in that directory.
Perl File Tests & their Meaning
-r To check if File/directory is readable by the current user/group
-w To check if File/directory is writable by the current user/group
-x To check if File/directory is executable by the current user/group
-o To check if File/directory is owned by the current user
-R To check if File/directory is readable by this real user/group
-W To check if File/directory is writable by this real user/group
-X To check if File/directory is executable by this real user/group
-O To check if File/directory is owned by this real user
-e To check if File/directory name exists
-z To check if File exists and has zero size (always false for directories)
-f To check if Entry is a plain file
-d To check if Entry is a directory
-l To check if Entry is a symbolic link
-S To check if Entry is a socket
-p To check if Entry is a named pipe (a “FIFO”)
-b To check if Entry is a block special file (like a mountable disk)
-c To check if Entry is a character special file (like an I/O device)
-u To check if File or directory is setuid
-g To check if File or directory is setgid
-k To check if File or directory has the sticky bit set
The given filehandle is a TTY (as by the isatty() system function, filenames can’t be
-t
tested by this test)
-T To check if File looks like a “text” file
-B To check if File looks like a “binary” file
-M To check Modification age (measured in days) of file
-A To check Access age (measured in days) of file
-C To check Inode-modification age (measured in days) of file
Perl Subroutine
What is Subroutine?
Subroutines are similar to functions in other programming languages. We have already
used some built-in functions like print, chomp, chop, etc. We can write our own
subroutines in Perl. These subroutines can be written anywhere in the program; it is
preferable to place the subroutines either at the beginning or at the end of the code.

Subroutines Example
sub subroutine_name
{
Statements…; # this is how typical subroutines look like.
}
Now that, we know how to write a subroutine, how do we access it?
We need to access or call a subroutine using the subroutine name prefixed with ‘&’
symbol.
sub display
{
print "this is a subroutine";
}
display(); # This is how we call a subroutine
Passing Perl Parameters & Perl arguments
Subroutines or perl function are written to place the reusable code in it. Most of the
reusable code requires parameters to be passed to the subroutine. Here, we will learn how
we can pass arguments to the subroutine.
sub display
{
my $var=@_; # @_ is a special variable which stores the list of arguments passed.

print "$var is the value passed";


}
display(2,3,4); #this is how we need to pass the arguments.
Output:
3 is the value passed
@_ is a special array variable which stores the arguments passed to the subroutines.
Perl Shift
We can also use ‘shift’ keyword which shifts one parameter at a time to a variable or
$_[0],$_[1]… which is an individual element of @_ array
sub display
{
my $var=shift;
print "$var is passed";
}
display("hello");
Output:
hello is passed
Subroutines are typically used in object-oriented programming and also in places where
you may have more reusable code to be placed.
Main functionality of subroutines is to do some task and return the result of the reusable
code.

We can return a value from subroutine using the return keyword.


sub add
{
my $a=shift;
my $b=shift;
return($a+$b);
}
my $result=add(5,6);
print $result;
Output:
11
$result will be holding the value of the $a and $b added.
We can also pass hashes and array directly to the subroutine.
sub hash
{
my %hash=@_;
print %hash;
}
%value= ( 1=>'a', 2=>'b');
&hash(%value);
Output:
1a2b
We can also return a hash or an array.
sub hashArray
{
my %hash=@_;
print "Inside Sub-routine";
print %hash;
return(%hash);
}
%hash=(1=>'a', 2=>'b');
my(@ret)=hashArray(%hash);
print "After Sub-routine call";
print @ret;
Output:
Inside Sub-routine2b1aAfter Sub-routine call2b1a
Perl Format
Perl has a mechanism using which we can generate reports. Using this feature, we can
make reports exactly the way we want while printing on the Output screen or in a file. A
simple format can be written using printf or sprintf functions available in Perl.
printf "%05d\n", 30;
This will include leading zeros in front of number 30 making a total count of digits to 5.
The same can be used for sprintf.
sprintf "%05d\n", 30; # This will print the same as printf.
Using printf and sprintf, we can obtain most of the Perl formats. In the case of reports, it
will be difficult to implement.
Example of a Report:
=====================================================
======================
Name Address Age Phone
=====================================================
======================
Krishna Chennai 24 929309242
Shruthi Chennai 24 929309232
The above is a example reports that we need to print in the same manner in Perl. This can
be achieved by using the perl printf and perl sprintf. It can effectively be implemented
using format.
A format can be declared in the below manner.
format FORMATNAME=FORMATLIST.
Here, we will be using a particular method write to print the data onto output screen or into
the file.
Symbol Description
@ Used to represent the start of the field holder
> Right alignment of text
< Left alignment of text
| Center alignment
# Numeric if multiple # provided. Assumes as a comment if single # provided
. Decimal point
^ Start of field holder can also be used for multiline and also for the word-wrap
~ Line should be empty if the variable is empty
@* Multiple lines.
($name,$addr,$age,$phone)=("krishna","chennai","24","929309242");
write;
($name,$addr,$age,$phone)=("shruthi","chennai","24","929309232");
write;
format STDOUT_TOP=
===============================================================
NAME ADDRESS AGE PHONE
===============================================================
.
format STDOUT=
@<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<< @<<< @<<<<<<<<<<
$name, $addr, $age, $phone
.
Execute the code to see the output.
We are using @ symbol to specify the start of the field holder or string, ‘<‘ each character.
We are using STDOUT to print on the standard output. We can change this to file handler
which we are using to write data into the file.
open(REPORT,">test.txt");
($name,$addr,$age,$phone)=("krishna","chennai","24","929309232");
write REPORT;
($name,$addr,$age,$phone)=("shruthi","chennai","24","929309232");
write REPORT;
format REPORT_TOP=
===============================================================
NAME ADDRESS AGE PHONE
===============================================================
.
format REPORT=
@<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<< @<<< @<<<<<<<<<<
$name, $addr, $age, $phone
We can replace ‘<‘ to ‘>’ or ‘|’ to change the alignment of the text.STDOUT_TOP is used
to design the header of the format.We can also use the same with file handler using
FH_TOP( FH is the file handler).This will output the format to the file which we are
working on.
Perl Coding Standards
Each programmer will have his own sense of writing the code using certain standards;
these standards should be familiar enough that other programmer can understand and
support the code properly.

Coding Standards in Perl


Writing code is simple and easy. The problem arises when it needs to be maintained at
later stages. Proper guidelines and coding standards need to be followed while writing the
code. Perl also defines certain standards that will be useful for programmers to write code.
It is advisable to load ‘strict’ and ‘warnings module’ while writing the code. Each of these
modules has its own importance. Strict will make us declare the variable before using and
also will tell if any bare word present in your code. Warnings module can alternatively be
used by passing ‘-w’ option to the Perl interpreter in shebang. Warnings will print on the
output screen.
#!/usr/bin/perl –w
Below are few lists of standards.

 Use ‘strict’ and ‘warnings’ module.


 Remove variable, which is not in use.
 Variable names should be understandable to other users. Ex: $name, @fileData etc.
 Documentation is required while coding a script.
 Do not hardcode any values, rather try to fetch those dynamically or ask the user to
enter during runtime.(File path, File names).
 Maximize code reuse. Try to put the reusable code in subroutines.
 Meaning full names should be given for subroutines.
 Subroutines need to written with appropriate comments and documentation.
 Always initialize variables.
 Always check the return codes for system calls. Opening a file may or may not
happen, having a return code here will display the error status if the file does not
exist.
Ex: open(FH, <file.txt”) or die(“cannot open the file $!”);

 Subroutine should always return a value.


 Open curly in the same line.
 Single line BLOCK may be placed in a single line with curly.
 Use labels during the LOOPS, it would be easy to exit from the loop whenever it is
necessary.
 Use underscore while long phrases of words are written as a variable name or
subroutine.
 Try to use simple regex while coding.
Perfect example with coding standards:
#######################################################################
Program to read the file content
# Date: 22-2-2013
# Author : Guru99
########################################################################
#!/usr/bin/perl
use strict;
use warnings;
my $line;
open FR, "file.txt" || die("Cannot open the file $!");
while ($line=<FR>)
{
print $line;
} # Looping file handler to print data
Perl Error Handling
What is an Exception?
An exception is an event that occurs during the program execution which will suspend or
terminate your program.
Error Handling
Error Handling is one which every programmer has to take care during programming. Perl
also provides error handling techniques with which we can trap the error and handle those
accordingly.

Error Handling in Perl


There are many ways to check for error in the program. We need to examine the return
codes of the function that we are using code. If we are able to handle those return codes
properly, then most of the error handling can be achieved.
What will return in case of system calls?
In the case of system calls, the return status will get stored in two special variables $? And
$!
$! – This will catch the error number or error number associated with the error message.
$? – This will hold the return status system() function.
Using Perl operator or Logical
We can use logical or operator for error handling while using system calls.
Ex:
open(FH,"<test.txt");
This will open the file in read mode if the file exists.
What if the file is missing?
open(FH,"<test.txt") or die("File not exists $!"); # This will perl exit the program if the file
not exists.
open(FH,"<test.txt") or warn ("File not exists $!"); # This will print a warning message on
STDERR
Perl Eval
Eval function can handle fatal errors, compile time errors, runtime errors and those errors
which terminates your code at some point in time.
Perl Eval function can have a block of code or an expression. Evals considers everything
placed in it as a string.
Consider a situation of calling a subroutine which is not defined in the script. In this
situation, the script terminates stating “undefined subroutine &XYZ, this error can be
handled in the eval function.
There are many uses of evals block; one such use is when we want to load the module
which is specific to the operating system during runtime.
Ex: Divide by zero causes a fatal error; to handle this we can place the code in evals block.
$a=5;
$b=0;
eval
{
'$result=$a/$b';
}
if($@)
{
print "$@"; # All the error codes returned by evals will get stored in $@.
}
Output:
syntax error at C:\Users\XYZ\Text.pl line 8, near “)
{“
Execution of C:\Users\XYZ\Text.pl aborted due to compilation errors.
Example: eval using perl die statement.
sub test
{
die "Dieing in sub test \n";
}
eval
{
test();
};
print "Caught : $@\n";
Output:
Caught : Dieing in sub test
Using Perl Try
Perl does not support try, catch and finally code blocks as other programming languages.
We can still use them by loading an external Perl module.
use Try::Tiny;
Using this we can place your code in try block and catch the error in warn block.
In place of $@ used in eval Try::Tiny uses $_.
# handle errors with a catch handler
try
{
die "Die now";
}
catch
{
warn "caught error: $_"; # not $@
};
Using finally.
my $y;
try
{
die 'foo'
}
finally
{
$y = 'bar'
};

try
{
die 'Die now'
}
catch
{
warn "Returned from die: $_"
}
finally
{
$y = 'gone'
};
Output:
foo at C:\Users\XYZ\Text.pl line 4.
We can use try, catch and finally in this manner.
try { # statement }
catch {# statement }
finally { # statement };
Or
try
{
# statement
}
finally
{
# statement
};
Output:
Or
try
{
# statement
}
finally
{
# statement
}
catch
{
# statement
};
Output:
Perl Socket programming
What is a socket?
The socket is a medium through which two computers can interact on a network by using
network address and ports.
Suppose, A (Server) and B (Client) are two systems, which has to interact with each other
using Sockets for running some programs.
To implements this we need to create sockets in both A (Server) and B (Client), A will be
in the receiving state and B will be in the sending state.
A (Server):
Here, the server wishes to receive a connection from B (Client) and execute some tasks
and send the result back to B (Client). When we execute the code, the operating system in
A tries to create a socket and binds one port to that socket. Then it will listen from the
sender which is B.
B (Client).
Here, the client wishes to send some program from his system to A (Server) for some
processing. When we execute the code, the operating system in B tries to create a socket
for communicating with A (Server), B has to specify the IP address and the port number of
A to which B wishes to connect.
If this goes well, both systems will interact to exchange the information through one port.
Perl also supports socket programming.
Perl has a native API through which sockets can be implemented. To make it easy, there
are many CPAN modules using which we write socket programs.
Server operations:

 Create Socket
 Bind socket with address and port
 Listen to the socket on that port address
 Accept the client connections which tries to connect using the port and IP of the
server
 Perform operations
Client Operations:

 Create Socket
 Connect to Server using on its port address
 Perform operations

Socket.io
This is one module for socket programming, which is based on object oriented
programming. This module does not support the INET network type used in networks.
IO::Socket::INET:
This module supports INET domain and is built upon IO::Sockets. All the methods
available in IO::Sockets are inherited in INET module.
Client and Server using TCP protocol:
TCP is a connection-oriented protocol; we will be using this protocol for socket
programming.
Before proceeding further let’s see how can we create an object for IO::Socket::INET
module and create a socket.
$socket = IO::Socket::INET->new(PeerPort => 45787,
PeerAddr => inet_ntoa(INADDR_BROADCAST),
Proto => udp,LocalAddr =>
'localhost',Broadcast => 1 )
or
die "Can't create socket and bind it : $@n";
The new method in IO::Socket::INET module accepts a hash as an input parameter to the
subroutine. This hash is predefined, and we just need to provide the values to the keys
which we want to use. There is a list of keys used by this hash.
PeerAddr Remote host address
PeerHost Synonym for PeerAddr
PeerPort Remote port or service
LocalAddr Local host bind address
LocalHost Synonym for LocalAddr
LocalPort Local host bind port
Proto Protocol name (or number)
Type Socket type
Listen Queue size for listen
ReuseAddr Set SO_REUSEADDR before binding
Reuse Set SO_REUSEADDR before binding
ReusePort Set SO_REUSEPORT before binding
Broadcast Set SO_BROADCAST before binding
Timeout Timeout value for various operations
MultiHomed Try all addresses for multihomed hosts
Blocking Determine if connection will be blocking mode
Server.pl
use IO::Socket;
use strict;
use warnings;
my $socket = new IO::Socket::INET (
LocalHost => 'localhost',
LocalPort => '45655',
Proto => 'tcp',
Listen => 1,
Reuse => 1,
);
die "Could not create socket: $!n" unless $socket;
print "Waiting for the client to send datan";
my $new_socket = $socket->accept();
while(<$new_socket>) {
print $_;
}
close($socket);
Client.pl
use strict;
use warnings;
use IO::Socket;
my $socket = new IO::Socket::INET (
PeerAddr => 'localhost',
PeerPort => '45655',
Proto => 'tcp',
);
die "Could not create socket: $!n" unless $socket;
print $socket "Hello this is socket connection!n";
close($socket);
Note:
In socket programming, we will have to execute Server.pl first and then client.pl
individually in different command prompts if we are running on local host.
What is Perl Modules and Packages
Modules and Packages are closely related to each other and are independent. Package: A
Perl package is also known as namespace and which have all unique variables used like
hashes, arrays, scalars, and subroutines. Module: Module is a collection of reusable code,
where we write subroutines in it. These modules can be loaded in Perl programs to make
use of the subroutines written in those modules.
What are Perl Modules?
Standard modules will get installed during installation of Perl on any system. CPAN:
Comprehensive Perl Archive Network – A global repository of Perl modules. Our own
customized Perl Modules which can be written by us. Basically, A module when loaded in
any script will export all its global variables and subroutines. These subroutines can
directly call as if they were declared in the script itself. Perl Modules can be written
with .pm extension to the filename Ex : Foo.pm. A module can be written by using
‘package Foo’ at the beginning of the program.
Basic Perl module:
#!/usr/bin/perl
package Arithmetic;
sub add
{
my $a=$_[0];
my $b=$_[1];
return ($a+$b);
}
sub subtract
{
my $a=$_[0];
my $b=$_[1];
return ($a-$b);
}
1;
No Output
To use this Perl module, we have to place it in currently working directory.
We can load a Perl module using require or use anywhere in the code. The major
difference between require and use is, require loaded module during runtime and use loads
during compile time.
#!/usr/bin/perl
require
Arithmetic;
print Arithmetic::add(5,6);
print Arithmetic:: subtract (5,6);
Here, in the above example, we are accessing the subroutines using fully qualified module
name.
We can also access the package using ‘use Arithmetic’.
Exporter:
This module has a default functionality of importing methods.
#!/usr/bin/perl
package Arithmetic;
require Exporter;
@ISA= qw(Exporter); # This is basically for implementing inheritance.
@EXPORT = qw(add);
@EXPORT_OK = qw(subtract);
sub add
{
my $a=$_[0];
my $b=$_[1];
return ($a+$b);
}
sub subtract
{
my $a=$_[0];
my $b=$_[1];
return ($a-$b);
}
1;
@EXPORT array can be used to pass a list of variables and subroutines which by default
will be exported to the caller of the Module.
@EXPORT_OK array can be used to pass a list of variables and subroutines which will be
exported on demand basis, where the user has to specify while loading the module.
#!/usr/bin/perl
use
Arithmetic qw(subtract);
print add(5,6);
print subtract (5,6);
By default, add subroutine will be exported. Subtract method won’t be exported if it not
specified while loading the module.
Object Oriented Programming in Perl
In this section, we will learn how to create Perl Object oriented Modules. First, let’s see
what is the object? An object is an instance using which we can access, modify and locate
some data in any Perl module. This is nothing but making your existing Perl package,
variables and subroutines to act like class, objects, and methods in reference to other
Programming Languages.
Create Class
We already know how to create modules from the previous topic. The purpose of the class
is to store methods and variables. A Perl Module will have subroutines which are methods.
We need to access those variables and subroutines objects.
Perl Constructor
A constructor in Perl is a method which will execute and return us a reference with the
module name tagged to the reference. This is called as blessing the class. We use a
particular variable for blessing a perl class, which is bless.
#!/usr/bin/perl
package Arithmetic;
sub new
{
my $class=shift;
my $self={};
bless $self, $class;
return $self;
}
sub add
{
my $self= shift;
my $a=$_[0];
my $b=$_[1];
return ($a+$b);
}
sub subtract
{
my $self= shift;
my $a=$_[0];
my $b=$_[1];
return ($a-$b);
}
1;
The new method used as a constructor for a class, This constructor will create an object for
us and will return to the script which is calling this constructor.
#!/usr/bin/perl
use Arithmetic;
my $obj= Arithmetic->new();
my $result= $obj->add(5,6);
print "$result";
$result = $obj->subtract(6,5);
print "$result";
Here, we need to understand how the object created. Whenever we try to create an object
for the class, we need to use the full name of the class. Suppose, if the perl class is located
in some lib\Math\Arithmetic.pm. And, if we want to access this perl class from the lib
directory then we have to provide the entire path of to the class while calling in the script.
use lib::Math::Arithmetic;
my $obj = lib::Math::Arithmetic->new();
This is how the object creation in Perl happens.
@INC:
How does Perl script know where library module exists? Perl only knows about current
directory of the script and the Perl inbuilt library path. Whenever we use, and Perl module,
which is not located in the current directory or Perl library Path, the script will always fail.
About @INC, this is an array, which holds all directory paths where it has to look for the
Perl modules. Try to execute this command and see what will be the output.
perl –e "print @INC"
This will give some output, and that is the path where the lib Modules will be available.
Whenever we use any new library module, we need to tell Perl, interpreter, to look into
that particular location where Perl module is available.
push(@INC, "PATH TO YOUR MODULE");
Make this as your first line of code. This will tell your interpreter to look into that Path.
or use
lib Arithmetic; # List here is your Perl Module location
Perl Destructor
The destructor of an object is by default called at the end and before your script exits. This
is used to destroy your objects from memory.
PERL V/s Shell Scripting

 Programming in Perl does not cause portability issues, which is common when
using different shells in shell scripting.
 Error handling is very easy in Perl
 You can write long and complex programs on Perl easily due to its vastness. This is
in contrast with Shell that does not support namespaces, modules, object,
inheritance etc.
 Shell has fewer reusable libraries available. Nothing compared to Perl’s CPAN
 Shell is less secure. It’s calls external functions(commands like mv, cp etc depend
on the shell being used). On the contrary Perl does useful work while using internal
functions.
How PERL is used in Automation Testing
Perl is widely used in automation. It may not be the best programming languages in the
world but its best suited for certain types of tasks. Let’s discuss where & why Perl is used
for Automation Testing.
Storage Testing
What is Storage? Data stored in Files.
Suppose, we have a Storage related Test Case where we have to write data on one
partition, read it & verify that the data is written correctly.
This can be done manually, but can a manual tester perform the same 10000 times? It will
be a nightmare! We need automation
Best tool to automate anything related to storage is Perl because of its File Handling
Techniques, REGEX and powerful file parsing which consumes least execution time
compared to other programming languages.
Why we need to test storage? Think about large Data Centers where data will be flowing
continuously from one system to other system with 1000’s of records being stored per
second. Testing robustness of such storage mechanism is essential.
Many companies like HP, Dell, IBM and many server manufacture use Perl as an interface
to test functionality in Storage and Networking domains. NetApp is one such company
which completely works on Storage and uses Perl as the Programming language to
automate the test cases.
If you are interested in Perl Automation, then it would be advisable to learn about Storage
& Networking Concepts.
Server & Network Testing:
Server and Network Testing using Perl
PERL is widely used in server uptime and performance monitoring.
Consider a data center which has 100 hosts(servers). You are required to connect to each
host, execute some commands remotely. You also want to reboot the system and check
when it comes back online.
Manually doing this task for all 100 hosts will be a nightmare. But we can easily automate
this using PERL
Design steps to achieve this above automation using PERL
1. Take input from file about the host info like (IP, Username, and Password).
2. Use Net::SSH2 to connect to each system and establish a channel to execute the
commands.
3. Execute set of commands required ex: ls, dir, ifconfig,ps etc.
4. Reboot the system.
5. Wait for 10minutes for the system to come up.
6. Ping the system using Net::Ping module and print the status.
We will code the above scenario.
Let’s take a file called Input.txt which will store the complete info about all the hosts in
which we need to connect and execute the command.
Input.txt
192.168.1.2 root password
192.168.1.3 root password
192.168.1.4 root root123
HostCheck.pl
use Net::SSH2;
use Net::Ping;
use strict;
use warnings;
my $ping = Net::Ping->new(); # Creating object for Net::Ping
my $SSHObj = Net::SSH2->new(); #Creating object for Net::SSH2
open( FH, "Input.txt" ); # Opening file and placing content to FH
my @hosts = <FH>;
my $ip;
my @ips;
foreach (@hosts)
{
if ( $_ =~ /(.*)\s+(\w+)\s+(.*)/ ) #Regex to get each info from file
{
$ip = $1;
my $user = $2;
my $password = $3;
$SSHObj->connect($ip);
print "Connecting to host -- $ip --Uname:$user --Password:$password\n";
my $status = $SSHObj->auth_password( $user, $password );
print "$status\n";
die("unable to establish connection to -- $ip") unless ($status);
my $shell = $SSHObj->channel();
print "$_\n" while <$shell>;
$shell->blocking(1);
$shell->pty('tty');
$shell->shell();
sleep(5);
#Executing the list of command on particular host. Can be any command
print $shell "ls \n";
print "$_\n" while <$shell>;
print $shell "ps \n";
print "$_\n" while <$shell>;
print $shell "dir \n";
print "$_\n" while <$shell>;
print $shell "init 6\n"; #rebooting the system
push( @ips, $ip );
}
}
sleep 600;
foreach (@ips)
{
if ( $ping->ping($_) )
{
print "$_ is alive.\n" if $ping->ping($_);
}
else
{
print "$_ is not still up --waiting for it to come up\n";
}
}
Web Testing
Perl is not only restricted to Storage & Network testing. We can also perform Web-based
testing using PERL. WWW-Mechanize is one module used for web testing. Basically, it
won’t launch any browser to test the functionality of web application’s rather it uses the
source code of the html pages.
We can also perform browser based testing using Selenium IDE, RC, Web driver. Perl is
supported for Selenium.
\n”; #this will hold remaining string after patter match is done.
print “

You might also like