Unit 1 Notes - PERL
Unit 1 Notes - PERL
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.
#!/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:
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:
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
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.
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.
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 “