PERL Tutorial for Beginners - Complete Guide

This tutorial is written assuming that you have a basic knowledge of programming and some common terms used in the world of programming.

Even if you are trying your hand in programming for the first time, with little effort you can grasp what is being taught in this tutorial.

In this tutorial, you will learn-

What is PERL?

Perl stands in for "Practical Extraction and Reporting Language" even though there is no official acronym for Perl. You may create your own acronym and no one will mind. Perl was created by Larry Wall in 1987 when he was working on a bug reporting system and "AWK"- a programming language he was using for the purpose was not helping him much. He is still the chief architect and developer of Perl. If we want to define Perl in one statement: Perl is a high level, interpreted, dynamic programming language. Did it all sound Greek to you? (Unless you actually know Greek).

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 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. Interpreter is piece of software which converts the program written in 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 can be implemented in many fields. The most popular use of Perl is in Web development. CGI programming is what Perl is most widely used for. CGI stands for Common Gateway interface. CGI programs are the most common way for Web servers to interact dynamically with users. Many web pages that contain forms, use a CGI program to process the form's data, once it's submitted. There is a complete chapter dedicated to CGI programming, so you learn about it in details later in the tutorial. Apart from CGI programming, Perl is also used to automate many tasks in the Web servers, and other administration jobs, it can automatically generate mails 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.

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. Its 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 tutorial, you will learn how you can code small, quick programs for specific tasks. Lets 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

print "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.

Pros: Cons:
  • Compared to other Programming languages Perl is most powerful for text handling and Parsing
  • This is an interpreted language with fast execution time as there is no need to compile a Perl script
  • Simple and easy to program and understand.
  • It is object oriented.
  • CPAN library eases PERL development (we will learn more about this later in the subject).
  • Used in Web development for mostly Payment Gateways.
  • Used in Automation and to test most of the Network and Storage related stuff.
  • There is minimal GUI support as compared to other Programming languages.
  • You need to refer to complex library modules which are not so easy to understand (Don't be scared once you know how to do the things everything will be easy).
  • Understanding complex Patterns requires experience.

Let's get started

With enough knowledge about the history of Perl and basic concepts of computer programming required for coding in Perl, it is time we take the dive and get started with Perl. The next chapter will teach you how you can setup Perl on your system and get ready for the coding journey in Perl. The tutorial will take Linux as the OS which students will be using for coding in Perl.

Download & Install PERL - Windows, Mac & Linux

How to get Perl?

Good news
you probably have it!

But if you can't find it already on your system, you can still get it for free.

To find out if you already have Perl installed, go into the command line and type: perl -v

PERL Tutorial for Beginners - Complete Guide

The command will display version of Perl if it's installed. In this case, the version is v5.14.2. But if not… don't panic…

UnixPERL Tutorial for Beginners - Complete Guide Already Installed Comes pre-installed with PERL though you may need to update to the latest version.
Mac OS PERL Tutorial for Beginners - Complete Guide Already Installed OSX comes with Perl pre-installed, although you may need to updated it to the latest version
WindowsPERL Tutorial for Beginners - Complete Guide Need to Install Two Options are available
  1. Strawberry Perl is an open source binary distribution of Perl for the Windows operating system. It includes a compiler and pre-installed modules that offer the ability to install XS CPAN modules directly from CPAN
  2. ActiveState perl provide a binary distribution of Perl (for many platforms), as well as their own Perl package manager (PPM)

Updating PERL on Linux:

If you need to update the Perl version then just enter one single line of command

sudo apt-get install perl

and relax. The rest will be taken care of. Just make sure you have an active internet connection.

Install perl for Windows:

First download the Active Perl from this link. Follow these steps to install ActivePerl on Windows system. See the below screenshots for the same.

Step 1:Once you download the installer and start the installation you will see the below window, click on next to proceed.

Step 2:Accept Licensing agreement to proceed the installation.

Step 3:Below are different packages that will be installed. By default, all will be selected. The only thing different is PPM (Perl Package Manager). This is the utility provided by Active Perl to install external Perl modules or libraries in your system. Click on Next to proceed.

Step 4:These are different types of Perl extensions that can be used for Perl. Mostly we will be using .Pl, .Plx and .Pm for Perl. Perl modules basically use .Pm as their file extension to refer as a library file. Select all the options and click on the Next button.

Step 5:Click on Install button to proceed with the installation.

Step 6: Once installed, execute the command 'Perl –v' to check whether Perl is successfully installed in your system.

There are lots of things which needs to be discussed for setting Perl environment in both Linux and Windows, as there won't be many library files included in this installation. You need to manually install those. You can install those manually using CPAN(Comprehensive Perl Archive Network) or either PPM which works only for perl windows. But these files are not mandatory to start coding in PERL. First PERL Program

Hello world!

Perl Example: Hello World

use warnings;
#this is just a comment…
print "Hello World";

Don't worry if you don't understand this text. Everything will be clear soon. Come on and take a look at it by line:


This tells the Operating System to execute this file with the program located at /usr/bin/perl. Some IDEs don't need this line. If it's essential you must write here path to your interpreter. Remember! This special line must be at the beginning of your program and must starts from #! use warnings; This is another special command which tells interpreter to display any warnings.

print "Hello World";

The print instruction writes text to the screen. The semicolon at the end of the line tells the perl interpreter that the instruction is finished. You must put a semicolon at the end of every instruction in Perl code. Note the quotation mark("). It's necessary for print instruction. Save the above script as

On Windows

If you have an Strawberry installed, you can simply click on Run. You can also run command-line interface and write on the console:

C:\> perl path\

or, if perl.exe is not in your path:

C:\> c:\perl\bin\perl.exe

On Linux/Unix

You just have to open the Terminal and write:


If you can't run the program, make sure you have eligibility to run it. Type on the Terminal:

chmod +x

Your program is now executable and ready to run. To execute, write:


Install cpan minus modules

Modules are set of codes that are used to do tasks that perform common operations in several programs. If you use perl modules you do not have to re write the codes to perform that same operation. Perl can make use of such external libraries of codes. One of the best library is the CPAN. It stands for Comprehensive Perl Archive Network, and contains a vast amount of Perl modules for you to use. It is a community or network of large number of developers who contribute such modules. By installing support for CPAN modules in your perl module, you can make use of the CPAN modules and make your work easier. Most Perl modules are written in Perl, some use XS (they are written in C) so require a C compiler (it's easy to get this setup - don't panic. Modules may have dependencies on other modules (almost always on CPAN) and cannot be installed without them (or without a specific version of them). It is worth thoroughly reading the documentation for the options below. Many modules on CPAN now require a recent version of Perl (version 5.8 or above). Install cpanminus a script to get, unpack, build and install modules from CPAN to make installing other modules easier (you'll thank us later). To Install App-cpanminus perl modules, in the command line type:

cpan App::cpanminus

cpan App::cpanminus Make sure you have internet connection while perl modules are being downloaded and installed.

Now install any module:

cpan –i <Module_Name>.

Lets see an example of installing a module File::Data(Its an Interface to access File Data).

Perl Variable

Now, we'll talking 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:

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 our name of variable).

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 $calar.
  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 in two words.`But the First character cannot be a number`````
  3. Even though numbers can be part of 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:

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

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 ours programs.

Two Types of Scalar Data Types

  1. Numbers
  2. Strings


In this type of scalar data we could specify:

  • integers, simply it's a whole numbers, like 2, 0, 534
  • floating-point numbers, it's a 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:

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.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 decimal system. Allow me to show you Octal, Hexadecimal and Binary representation. A short table present all important information about this weird styles:

Representation Base Proceded 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 this values for Perl means the same.Perl doesn't store the values in the same format .It will internally converts these hexadecimal, binary, octal to decimal values. Give me a value! Few words about Variable Assignment… Assignment is the most common operation on a scalar, and it's very simple. Perl use 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: It's also very simple type of scalar.

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 computer memory. Typically this is just sequences of letter and punctuation in the ASCII code.

PERL Tutorial for Beginners - Complete Guide

Like numbers, strings two different types:

  • Single quotes string literals
  • Double quotes string literals

Single-quoted string literals

Single quotation marks are used to enclose data you want taken literally. A short example and everything should be clear:

Perl Examples:

$num = 7;
$txt = 'it is $num';
print $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;

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 &#92n

Consider the following program

Perl Examples:

print "hello &#92n";

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 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. Everything is in the table:

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 lovercase 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 right side of the equal sign and puts this string to 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;

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:


$a = "Tom, Ann\'s";

$c = "favorite cat";

$c = $a ." mother". $c;

print $c;

The strings

"$a", "$b", "$c" is concatenated 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 upon the operator (we'll talk about operators later, now, just accept there are a lot of operators, different for numbers and strings) If operator expects a number, Perl will use the value as a number. If operator expects a string, Perl will use the value as a string. In the 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;

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.


my $var=5;



my $var_2 =$var;


print $var_2;

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.

$var = 5;
local $var = 3;
print "local,&#92$var = $var &#92n";

print "global,&#92$var = $var &#92n";

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


use strict;

This will help you writer 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

use strict;
$var = 10;

print "$var";

Result : Error

use strict;
my $var = 10;
print "$var";

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;

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.

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

Suppose you want to assign a value to 5th 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;

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 size of an array without using functions? Yes, we can.

@array= qw/a b c d e/;
print $size=scalar (@array);
print "&#92n";
print $size=$#array + 1;                                          # $#array will print the Max Index of the array, which is 4 in this case

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;
print "$_ &#92n";                                                      # This is a special variable which store the current value.


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&#92n";
push(@days, "Thu");	                                             # adds one element at the end of an array
print "2nd when push : @days&#92n";
unshift(@days, "Fri");	                                          # adds one element at the beginning of an array
print "3rd when unshift : @days&#92n";
print "4th when pop 	: @days&#92n";	                # 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&#92n";


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 tutorials.

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 array using indices. But, is this good idea to use 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 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 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;

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.

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

Add Perl Hashes

As, you can see we already have a hash %newHash and now we need to add more entries in to it.




print %newHash;

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 of function of Perl. Here, we will see an example for assigning a hash to an array.

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);


print "@arraykeys&#92n";

print "@arrayvalues&#92n";    # \n to print new line.

To remove all the entries in 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;
print "The value is $a";

Perl If Else

This looks good. Let us think about a situation where $a is not 5.

my $a=10;

print "The values is $a ---PASS";


print "The value is $a ---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;
print "Executed If block -- The value is $a";

print "Executed elsif block --The value is $a";




print "Executed else block – The value is $a";


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
  print "Inside 1st if block";
                print "Inside 2nd if block --- The value is $a";
                print " Inside 2nd else block --- The value is $a";
        print "Inside 1st else block – The value is $a";

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;

print "Inside the unless block --- The value is $a";




print "Inside else block--- The value is $a";


Guess what will be the output. You are right!!!!!. The output will be the print statement of else block. Because 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";




print "Inside else block"

Using unless

$a= " This is Perl";
unless($a eq "SASSDSS"){
print "Inside unless Block";
print "Inside else 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 "&#60br&#47&#62";

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.

	print "$_ n";
        print "&#60br&#47&#62";

Perl Foreach

Foreach 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&#60br&#47&#62";

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);
print " The value is $_ &#60br&#47&#62";# This is same as the above code.

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 &#60br&#47&#62";


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 &#60br&#47&#62";

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 name provided as 'sai'.

$guru99 = 0;
while ($guru99 <= 7) {
	print "&#60br&#47&#62";
	$guru99 ++;
print "Finished Counting!";

In the above example, the while condition will be true only if we enter input other than 'sai'.

If you see how while works here, the code block will execute only if the condition in while is true.

Perl do-while

Do while loop will execute at-least once even if the condition in while is false.

Let's take the same example by using do while.

 $guru99 = 10;
 do {
 print "$guru99 &#60br&#47&#62";
 while ($guru99 >= 1);
 print "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 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 &#92n";

 my $name=<STDIN>;


 until($name ne 'sai')


    print "Enter any name &#92n";




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 &#92n";

 my $name=<STDIN>;




     print "Enter any name &#92n";



 }until($name ne '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.





Addition operation used for adding two values or variables

holding values

$x=5+6; # or




Subtraction operator used for subtracting two values or variables holding values

$x=6-5; # or




Multiplication operator used for multiply two values or variables holding values

$x=6*5; # or




Division operator used for divide two values or variables holding values

$x=36/6; # or




Exponential operator used for provide exponent and get the value.

Ex : 22 = 4, 33 = 27

$x=5**5; # or





Modulus operator used to get the reminder during division of two values or variables holding values

$x=5%2; # or



$z=$x % $y;


Unary addition operator to increment value of a variable by 1






Unary Subtraction operator to decrement value of a variable by 1


$x--; # post increment


--$x;# pre increment

Example to complete all the above operations.

my $x=10;

my $y=2;

my $z;


print ("Add of $x and $y is $z <br/>");


print ("Sub of $x and $y is $z <br/>");


print ("Mul of $x and $y is $z <br/>");


print ("Div of $x and $y is $z <br/>");


print ("Exp of $x and $y is $z <br/>");


print ("Mod of $x and $y is $z <br/>");

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.





Addition operator used for adding and assigning the value to same variable




Subtraction operator used for subtracting and assigning the value to same variable




Multiplication operator used for adding and assigning the value to same variable




Division operator used for dividing and assigning the value to same variable




Exponential operator used for getting exponent and assigning the value to same variable




Modulus operator used for getting a reminder during division and assigning the value to same variable



Example to complete all the above operations.

my $x=10;


print("Add = $x<br/>");


print("Sub= $x<br/>");


print("Mul = $x<br/>");


print("Div = $x<br/>");

Logical and Relational Operators:

Perl uses logical operators to compare numbers and strings. Most of the time logical operators are used in Conditional Statements.



==or eq

Operator used to check whether both variables are equal

!=Or ne

Operator used to check whether both variables are not equal

> or gt

Operator used to check whether

A is greater than B

<or lt

Operator used to check whether

A is less than B

>=or ge

Operator used to check whether

A is greater than or equal to B

<=or le

Operator used to check whether

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 <br/>");
print ("False -- not equal $x and $y<br/>");
if($x != $y){
print ("True -- not equal $x and $y<br/>");
print ("False -- equal $x and $y<br/>");
if($y > $x){
print ("True -- $y greater than $x<br/>");
print ("False -- $y greater than $x<br/>");
if($x < $y){
print ("True -- $x less than $y<br/>");
print ("False -- $x less than $y<br/>");
if($x <= $y){
print ("True -- $x less than $y<br/>");
print ("False -- $x less than $y<br/>");
if($y >= $x){
print ("True -- $y greater than $x<br/>");
print ("False -- $y greater than $x<br/>");

You can see examples of logical operators in later sections.

Perl Special Variables

What is Perl Special Variables?

Special variables in Perl are those which have some predefined meaning. These variables denoted with either real Name or Punctuation symbols. We have 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
$_$ARG This is the default variable which stores the current 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 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.
$-$FORMAT_LINES_LEFT Holds the value of the number of lines left to print from the page.
$~$FORMAT_NAME Format Name: Holds the format of the currently selected output by default the file handle name.
$^$FORMAT_TOP_NAME Holds the value of the heading format of the file handler, by default value will be _TOP followed by file handle name.
$|$OUTPUT_AUTOFLUSH Default is zero; this is used to flush the output buffer after every write() or print().
$$ Will hold the running process number of Perl interpreter.
$? Status code : Pipe and system call. Return status of the command executed.
$&$MATCH Used in regular expressions, this will hold a string of the last successful pattern match.
$`$PREMATCH Used in regular expressions, this will hold string preceded by last successful pattern match.
$'$POSTMATCH Used in regular expressions, this will hold a string that followed by the last successful pattern match.
$+$LAST_PAREN_MATCH Holds the string of the last bracket that is matched by the last pattern search.
$<digit> $1, $2, $3 …. Holds the values of the pattern matched in order.
$[ First index: Array, substring.
$] Version of Perl.
$" Separator used for list elements, by default value is a white space.
$; 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.
$^C Holds the current value of the flag when –c command line switch is used.
$^F Maximum system file descriptor, by default value is set to 2
$^I$INPLACE_EDIT Holds the value of –i command line switch.
$^M Special Memory pool, can be used when Perl script dies with out-off memory error.
$^O$OSNAME Operating system info is stored. 'Linux' for Linux systems, 'mswin32' for Windows systems.
$^T$BASETIME The time when the scripts running in seconds.
$^W$WARNING The current value of the –w command line switch. Warning switch.
$ARGV Name of the current file, when <> is used.

Array Special Variables:

Variable Description
@INC Holds a list of paths, where Perl library modules or scripts can be looked into while executing the current script. This @INC is used by use and require statements to look into those paths for library modules.
@ARGV Stores the command line arguments passed.
@_ Used in subroutines, while passing the parameters to the subroutines.
@F This is the array into which the input lines are stored when auto split –a (command line switch is used).

Hash Special Variables:

Variable Description
%INC File name will be the keys; values will be the path to those files. Used by do, use and require.
%ENV System environmental variables.
%SIG Signals handler.

Perl Examples:

my $str= "Hello World";

$str =~ /llo/;

print "$&\n";    # this will hold string of the last successful pattern match

print "$'\n";    #this will hold remaining string after patter match is done.

print "$`\n";    #this will hold the string before the patter match.

$\= "--";     #output record separator (Check output of print on output screen)

my $a =5;

my $b =6;

print "$a";

print "$b";


my @array = qw(a b c d);

print "";

$"="-";# output record separator arrays (Check output of print on output screen)

print "@array";

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

  • 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 patter 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";



print "Find Pattern";




print "unable to find the 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 with 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";
 print "true"; 
print "False"; 

This small code will print 'true', as the perl pattern matching identifies the string in 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";


print $a;


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";


print $a;


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 is done using FILE HANDLE. We have to define this FILE HANDLE during the opening a file for either read or write.

In this 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(FH,"<filename or complete path of the file"); 

Write – open(FH,">filename or complete path of the file"); 

Append – open(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.


while(<FH>)    # Looping the file contents using the FH as a filehandle. 


print "$_";


close FH;



my @content=<FH>; # specifying the input of the array is FH.



 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.


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.


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 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, "");



$a=tell FH;

print "$a";


Perl Seek

Seek function is similar to 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 beginning of the file.


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.


opendir(DIR,"C:\\Program Files\\");




print "$_\n";



This will print all the available files in that directory.


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 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 subroutine.

sub display


my $var=@_; # @_ is a special variable which store the list of arguments passed.

print "$var is the value passed";


&display(2,3,4);    #this is how we need to pass the arguments.

@_ 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";



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.

PERL Tutorial for Beginners - Complete Guide

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

sub add


my $a=shift;

my $b=shift;



my $result=&add(5,6);
print $result;

$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');


We can also return a hash or an array.

sub hashArray
my %hash=@_;
print "Inside Sub-routine";
print %hash;
%hash=(1=>'a', 2=>'b');
print "After Sub-routine call";
print @ret;


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 sprint 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 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.


Here, we will be using a particular method write to print the data on to 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 variable is empty
@* Multiple lines.



format STDOUT_TOP= 


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.



write REPORT; 


write REPORT; 

format REPORT_TOP= 

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.

PERL Tutorial for Beginners - Complete Guide

Writing code is simple and easy. 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 to 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 are not in use.
  • Variable names should be understandable to other users. Ex: $name, @fileData etc.
  • Documentation is required while coding a script.
  • Do not hard code 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.

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



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 of 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 are 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.

 print "$@";    # All the error codes returned by evals will get stored in $@. 

Example: eval using perl die statement.

sub test 
die "Dieing in sub test \n"; 
print "Caught : $@\n";

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

die "Die now"; 
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' };

We can use try, catch and finally in this manner.

try { # statement }

catch {# statement }

finally { # statement };


# statement 
# statement 


# statement 
# statement 
# statement 


Perl Socket programming

What is a socket?

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

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.


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 )
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 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 multi-homed hosts
Blocking Determine if connection will be blocking mode

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 $_; 

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"; 


In socket programming, we will have to execute first and then 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 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 : A module can be written by using 'package Foo' at the beginning of the program.

Basic Perl module:

package Arithmetic; 
sub add 
my $a=$_[0]; 
my $b=$_[1]; 
return ($a+$b);
sub subtract 
my $a=$_[0]; 
my $b=$_[1]; 
return ($a-$b); 

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. Major difference between require and use is, require loaded module during runtime and use loads during compile time.

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'.


This module has a default functionality of importing methods.

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);

@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.

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.

In this tutorial, you will learn-

Create Class

We already know how to create modules from the previous topic. The purpose of 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.

Perl Class

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); 

The new method used as a constructor for class, This constructor will create an object for us and will return to the script which is calling this constructor.

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\ 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.


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, 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 in to that particular location where Perl module is available.


Make this as your first line of code. This will tell your interpreter to look in to that Path. or use

lib Arithmetic; # List here is your Perl Module location

Perl Destructor

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.