Perl Tutorial
Perl Tutorial
Bioinformatics Scripting
Lab Manual
BIO400
1
Perl Tutorial for Beginners
Perl Tutorial
Perl is a programming language developed by Larry Wall, especially designed for text processing.
It stands for Practical Extraction and Report Language. It runs on a variety of platforms, such
as Windows, Mac OS, and the various versions of UNIX. This tutorial provides a complete
understanding on Perl.
Audience
This reference has been prepared for beginners to help them understand the basic to advanced
concepts related to Perl Scripting languages.
Prerequisites
Before you start practicing with various types of examples given in this reference, we are making
an assumption that you have prior exposure to C programming and Unix Shell.
Perl - Introduction
Perl is a general-purpose programming language originally developed for text manipulation and
now used for a wide range of tasks including system administration, web development, network
programming, GUI development, and more.
What is Perl?
• Perl is a stable, cross platform programming language.
• Though Perl is not officially an acronym but few people used it as Practical Extraction and Report
Language.
• It is used for mission critical projects in the public and private sectors.
• Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License
(GPL).
• Perl was created by Larry Wall.
• Perl 1.0 was released to usenet's alt.comp.sources in 1987.
• At the time of writing this tutorial, the latest version of perl was 5.16.2.
• Perl is listed in the Oxford English Dictionary.
PC Magazine announced Perl as the finalist for its 1998 Technical Excellence Award in the
Development Tool category.
Perl Features
• Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others.
• Perls database integration interface DBI supports third-party databases including Oracle, Sybase,
Postgres, MySQL and others.
• Perl works with HTML, XML, and other mark-up languages.
• Perl supports Unicode.
• Perl is Y2K compliant.
2
Perl Tutorial for Beginners
Perl is Interpreted
Perl is an interpreted language, which means that your code can be run as is, without a compilation
stage that creates a non portable executable program.
Traditional compilers convert programs into machine language. When you run a Perl program, it's
first compiled into a byte code, which is then converted ( as the program runs) into machine
instructions. So it is not quite the same as shells, or Tcl, which are strictlyinterpreted without an
intermediate representation.
It is also not like most versions of C or C++, which are compiled directly into a machine dependent
format. It is somewhere in between, along with Python and awk and Emacs .elc files.
Perl - Environment
Before we start writing our Perl programs, let's understand how to setup our Perl environment. Perl
is available on a wide variety of platforms −
$perl -v
If you have perl installed on your machine, then you will get a message something as follows −
This is perl 5, version 16, subversion 2 (v5.16.2) built for i686-linux
Perl may be copied only under the terms of either the Artistic License or
the
GNU General Public License, which may be found in the Perl 5 source kit.
Install Perl
Perl distribution is available for a wide variety of platforms. You need to download only the binary
code applicable for your platform and install Perl.
If the binary code for your platform is not available, you need a C compiler to compile the source
code manually. Compiling the source code offers more flexibility in terms of choice of features that
you require in your installation.
Here is a quick overview of installing Perl on various platforms.
4
Perl Tutorial for Beginners
NOTE − Here $ is a Unix prompt where you type your command, so make sure you are not typing
$ while typing the above mentioned commands.
This will install Perl in a standard location /usr/local/bin and its libraries are installed
in /usr/local/lib/perlXX, where XX is the version of Perl that you are using.
It will take a while to compile the source code after issuing the make command. Once installation
is done, you can issue perl -v command at $ prompt to check perl installation. If everything is fine,
then it will display message like we have shown above.
Windows Installation
Here are the steps to install Perl on Windows machine.
• Follow the link for the Strawberry Perl installation on Windows http://strawberryperl.com
• Download either 32bit or 64bit version of installation.
• Run the downloaded file by double-clicking it in Windows Explorer. This brings up the Perl install wizard,
which is really easy to use. Just accept the default settings, wait until the installation is finished, and you're
ready to roll!
Macintosh Installation
In order to build your own version of Perl, you will need 'make', which is part of the Apples developer
tools usually supplied with Mac OS install DVDs. You do not need the latest version of Xcode (which
is now charged for) in order to install make.
Here are the simple steps to install Perl on Mac OS X machine.
• Open a Web browser and go to https://www.perl.org/get.html.
• Follow the link to download zipped source code available for Mac OS X.
• Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt.
$tar -xzf perl-5.x.y.tar.gz
$cd perl-5.x.y
$./Configure -de
$make
$make test
$make install
This will install Perl in a standard location /usr/local/bin and its libraries are installed
in /usr/local/lib/perlXX, where XX is the version of Perl that you are using.
Running Perl
The following are the different ways to start Perl.
Interactive Interpreter
You can enter perl and start coding right away in the interactive interpreter by starting it from the
command line. You can do this from Unix, DOS, or any other system, which provides you a
command-line interpreter or shell window.
$perl -e <perl code> # Unix/Linux
5
Perl Tutorial for Beginners
or
1
-d[:debugger]
Runs program under debugger
2
-Idirectory
Specifies @INC/#include directory
3
-T
Enables tainting checks
4
-t
Enables tainting warnings
5
-U
Allows unsafe operations
6
-w
Enables many useful warnings
7
-W
Enables all warnings
8
-X
Disables all warnings
9
-e program
Runs Perl script sent in as program
10
file
Runs Perl script from a given file
6
Perl Tutorial for Beginners
or
Perl - Syntax Overview Before we start writing our Perl programs, let's unde
Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk,
Lisp and even English. However, there are some definite differences between the languages. This
chapter is designd to quickly get you up to speed on the syntax that is expected in Perl.
A Perl program consists of a sequence of declarations and statements, which run from the top to
the bottom. Loops, subroutines, and other control structures allow you to jump around within the
code. Every simple statement must end with a semicolon (;).
Perl is a free-form language: you can format and indent it however you like. Whitespace serves
mostly to separate tokens, unlike languages like Python where it is an important part of the syntax,
or Fortran where it is immaterial.
7
Perl Tutorial for Beginners
#!/usr/bin/perl
Comments in Perl
Comments in any programming language are friends of developers. Comments can be used to
make program user friendly and they are simply skipped by the interpreter without impacting the
code functionality. For example, in the above program, a line starting with hash # is a comment.
Simply saying comments in Perl start with a hash symbol and run to the end of the line −
# This is a comment in perl
Lines starting with = are interpreted as the start of a section of embedded documentation (pod),
and all subsequent lines until the next =cut are ignored by the compiler. Following is the example
−
Live Demo
#!/usr/bin/perl
8
Perl Tutorial for Beginners
=begin comment
This is all part of multiline comment.
You can use as many lines as you like
These comments will be ignored by the
compiler until the next =cut is encountered.
=cut
This will produce the following result −
Hello, world
Whitespaces in Perl
A Perl program does not care about whitespaces. Following program works perfectly fine −
#!/usr/bin/perl
#!/usr/bin/perl
#!/usr/bin/perl
9
Perl Tutorial for Beginners
#!/usr/bin/perl
$a = 10;
print "Value of a = $a\n";
print 'Value of a = $a\n';
This will produce the following result −
Value of a = 10
Value of a = $a\n$
"Here" Documents
You can store or print multiline text with a great comfort. Even you can make use of variables inside
the "here" document. Below is a simple syntax, check carefully there must be no space between
the << and the identifier.
An identifier may be either a bare word or some quoted text like we used EOF below. If identifier is
quoted, the type of quote you use determines the treatment of the text inside the here docoment,
just as in regular quoting. An unquoted identifier works like double quotes.
Live Demo
#!/usr/bin/perl
$a = 10;
$var = <<"EOF";
This is the syntax for here document and it will continue
until it encounters a EOF in the first line.
This is case of double quote so variable value will be
interpolated. For example value of a = $a
EOF
print "$var\n";
$var = <<'EOF';
This is case of single quote so variable value will be
interpolated. For example value of a = $a
EOF
print "$var\n";
This will produce the following result −
This is the syntax for here document and it will continue
until it encounters a EOF in the first line.
This is case of double quote so variable value will be
interpolated. For example value of a = 10
Escaping Characters
Perl uses the backslash (\) character to escape any type of character that might interfere with our
code. Let's take one example where we want to print double quote and $ sign −
Live Demo
#!/usr/bin/perl
Perl Identifiers
A Perl identifier is a name used to identify a variable, function, class, module, or other object. A
Perl variable name starts with either $, @ or % followed by zero or more letters, underscores, and
digits (0 to 9).
Perl does not allow punctuation characters such as @, $, and % within identifiers. Perl is a case
sensitive programming language. Thus $Manpower and $manpower are two different identifiers
in Perl.
1
Scalar
Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a
number, a string, or a reference. A reference is actually an address of a variable, which
we will see in the upcoming chapters.
2
Arrays
Arrays are ordered lists of scalars that you access with a numeric index, which starts with
0. They are preceded by an "at" sign (@).
3
Hashes
11
Perl Tutorial for Beginners
Hashes are unordered sets of key/value pairs that you access using the keys as
subscripts. They are preceded by a percent sign (%).
Numeric Literals
Perl stores all the numbers internally as either signed integers or double-precision floating-point
values. Numeric literals are specified in any of the following floating-point or integer formats −
Type Value
Integer 1234
Hexadecimal 0xffff
Octal 0577
String Literals
Strings are sequences of characters. They are usually alphanumeric values delimited by either
single (') or double (") quotes. They work much like UNIX shell quotes where you can use single
quoted strings and double quoted strings.
Double-quoted string literals allow variable interpolation, and single-quoted strings are not. There
are certain characters when they are proceeded by a back slash, have special meaning and they
are used to represent like newline (\n) or tab (\t).
You can embed newlines or any of the following Escape sequences directly in your double quoted
strings −
\\ Backslash
12
Perl Tutorial for Beginners
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
13
Perl Tutorial for Beginners
Example
Let's see again how strings behave with single quotation and double quotation. Here we will use
string escapes mentioned in the above table and will make use of the scalar variable to assign
string values.
Live Demo
#!/usr/bin/perl
Perl - Variables
Variables are the reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can
store integers, decimals, or strings in these variables.
We have learnt that Perl has the following three basic data types −
• Scalars
14
Perl Tutorial for Beginners
• Arrays
• Hashes
Accordingly, we are going to use three types of variables in Perl. A scalar variable will precede by
a dollar sign ($) and it can store either a number, a string, or a reference. An array variable will
precede by sign @ and it will store ordered lists of scalars. Finaly, the Hashvariable will precede
by sign % and will be used to store sets of key/value pairs.
Perl maintains every variable type in a separate namespace. So you can, without fear of conflict,
use the same name for a scalar variable, an array, or a hash. This means that $foo and @foo are
two different variables.
Creating Variables
Perl variables do not have to be explicitly declared to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.
Keep a note that this is mandatory to declare a variable before we use it if we use use
strictstatement in our program.
The operand to the left of the = operator is the name of the variable, and the operand to the right
of the = operator is the value stored in the variable. For example −
$age = 25; # An integer assignment
$name = "John Paul"; # A string
$salary = 1445.50; # A floating point
Here 25, "John Paul" and 1445.50 are the values assigned to $age, $name and $salaryvariables,
respectively. Shortly we will see how we can assign values to arrays and hashes.
Scalar Variables
A scalar is a single unit of data. That data might be an integer number, floating point, a character,
a string, a paragraph, or an entire web page. Simply saying it could be anything, but only a single
thing.
Here is a simple example of using scalar variables −
Live Demo
#!/usr/bin/perl
15
Perl Tutorial for Beginners
Array Variables
An array is a variable that stores an ordered list of scalar values. Array variables are preceded by
an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the
variable name followed by the index of the element in square brackets.
Here is a simple example of using array variables −
Live Demo
#!/usr/bin/perl
Hash Variables
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to
a single element of a hash, you will use the hash variable name followed by the "key" associated
with the value in curly brackets.
Here is a simple example of using hash variables −
Live Demo
#!/usr/bin/perl
16
Perl Tutorial for Beginners
Variable Context
Perl treats same variable differently based on Context, i.e., situation where a variable is being used.
Let's check the following example −
Live Demo
#!/usr/bin/perl
@copy = @names;
$size = @names;
1
Scalar
Assignment to a scalar variable evaluates the right-hand side in a scalar context.
2
List
Assignment to an array or a hash evaluates the right-hand side in a list context.
3
Boolean
Boolean context is simply any place where an expression is being evaluated to see
whether it's true or false.
4
Void
This context not only doesn't care what the return value is, it doesn't even want a return
value.
5
Interpolative
This context only happens inside quotes, or things that work like quotes.
17
Perl Tutorial for Beginners
Perl - Scalars
A scalar is a single unit of data. That data might be an integer number, floating point, a character,
a string, a paragraph, or an entire web page.
Here is a simple example of using scalar variables −
Live Demo
#!/usr/bin/perl
Numeric Scalars
A scalar is most often either a number or a string. Following example demonstrates the usage of
various types of numeric scalars −
Live Demo
#!/usr/bin/perl
$integer = 200;
$negative = -300;
$floating = 200.340;
$bigfloat = -1.2E-23;
18
Perl Tutorial for Beginners
integer = 200
negative = -300
floating = 200.34
bigfloat = -1.2e-23
octal = 255
hexa = 255
String Scalars
Following example demonstrates the usage of various types of string scalars. Notice the difference
between single quoted strings and double quoted strings −
Live Demo
#!/usr/bin/perl
Scalar Operations
You will see a detail of various operators available in Perl in a separate chapter, but here we are
going to list down few numeric and string operations.
Live Demo
#!/usr/bin/perl
19
Perl Tutorial for Beginners
str = helloworld
num = 15
mul = 20
mix = helloworld15
Multiline Strings
If you want to introduce multiline strings into your programs, you can use the standard single quotes
as below −
Live Demo
#!/usr/bin/perl
$string = 'This is
a multiline
string';
print "$string\n";
This will produce the following result −
This is
a multiline
string
You can use "here" document syntax as well to store or print multilines as below −
Live Demo
#!/usr/bin/perl
print <<EOF;
This is
a multiline
string
EOF
This will also produce the same result −
This is
a multiline
string
V-Strings
A literal of the form v1.20.300.4000 is parsed as a string composed of characters with the specified
ordinals. This form is known as v-strings.
A v-string provides an alternative and more readable way to construct strings, rather than use the
somewhat less readable interpolation form "\x{1}\x{14}\x{12c}\x{fa0}".
They are any literal that begins with a v and is followed by one or more dot-separated elements.
For example −
Live Demo
20
Perl Tutorial for Beginners
#!/usr/bin/perl
$smile = v9786;
$foo = v102.111.111;
$martin = v77.97.114.116.105.110;
Special Literals
So far you must have a feeling about string scalars and its concatenation and interpolation opration.
So let me tell you about three special literals __FILE__, __LINE__, and __PACKAGE__ represent
the current filename, line number, and package name at that point in your program.
They may be used only as separate tokens and will not be interpolated into strings. Check the
below example −
Live Demo
#!/usr/bin/perl
Perl – Arrays
An array is a variable that stores an ordered list of scalar values. Array variables are preceded by
an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the
variable name followed by the index of the element in square brackets.
Here is a simple example of using the array variables −
Live Demo
#!/usr/bin/perl
21
Perl Tutorial for Beginners
Array Creation
Array variables are prefixed with the @ sign and are populated using either parentheses or the qw
operator. For example −
@array = (1, 2, 'Hello');
@array = qw/This is an array/;
The second line uses the qw// operator, which returns a list of strings, separating the delimited
string by white space. In this example, this leads to a four-element array; the first element is 'this'
and last (fourth) is 'array'. This means that you can use different lines as follows −
@days = qw/Monday
Tuesday
...
Sunday/;
You can also populate an array by assigning each value individually as follows −
$array[0] = 'Monday';
...
$array[6] = 'Sunday';
#!/usr/bin/perl
22
Perl Tutorial for Beginners
print "$days[0]\n";
print "$days[1]\n";
print "$days[2]\n";
print "$days[6]\n";
print "$days[-1]\n";
print "$days[-7]\n";
This will produce the following result −
Mon
Tue
Wed
Sun
Sun
Mon
Array indices start from zero, so to access the first element you need to give 0 as indices. You can
also give a negative index, in which case you select the element from the end, rather than the
beginning, of the array. This means the following −
print $days[-1]; # outputs Sun
print $days[-7]; # outputs Mon
#!/usr/bin/perl
@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);
Array Size
The size of an array can be determined using the scalar context on the array - the returned value
will be the number of elements in the array −
@array = (1,2,3);
print "Size: ",scalar @array,"\n";
23
Perl Tutorial for Beginners
The value returned will always be the physical size of the array, not the number of valid elements.
You can demonstrate this, and the difference between scalar @array and $#array, using this
fragment is as follows −
Live Demo
#!/usr/bin/perl
@array = (1,2,3);
$array[50] = 4;
$size = @array;
$max_index = $#array;
1
push @ARRAY, LIST
Pushes the values of the list onto the end of the array.
2
pop @ARRAY
Pops off and returns the last value of the array.
3
shift @ARRAY
Shifts the first value of the array off and returns it, shortening the array by 1 and moving
everything down.
4
unshift @ARRAY, LIST
Prepends list to the front of the array, and returns the number of elements in the new
array.
24
Perl Tutorial for Beginners
Live Demo
#!/usr/bin/perl
#!/usr/bin/perl
@weekdays = @days[3,4,5];
print "@weekdays\n";
This will produce the following result −
Thu Fri Sat
The specification for a slice must have a list of valid indices, either positive or negative, each
separated by a comma. For speed, you can also use the .. range operator −
Live Demo
25
Perl Tutorial for Beginners
#!/usr/bin/perl
@weekdays = @days[3..5];
print "@weekdays\n";
This will produce the following result −
Thu Fri Sat
#!/usr/bin/perl
@nums = (1..20);
print "Before - @nums\n";
splice(@nums, 5, 5, 21..25);
print "After - @nums\n";
This will produce the following result −
Before - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After - 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20
Here, the actual replacement begins with the 6th number after that five elements are then replaced
from 6 to 10 with the numbers 21, 22, 23, 24 and 25.
#!/usr/bin/perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";
26
Perl Tutorial for Beginners
#!/usr/bin/perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";
print "$string1\n";
print "$string2\n";
This will produce the following result −
Rain-Drops-On-Roses-And-Whiskers-On-Kittens
Larry,David,Roger,Ken,Michael,Tom
Sorting Arrays
The sort() function sorts each element of an array according to the ASCII Numeric standards. This
function has the following syntax −
sort [ SUBROUTINE ] LIST
This function sorts the LIST and returns the sorted array value. If SUBROUTINE is specified then
specified logic inside the SUBTROUTINE is applied while sorting the elements.
Live Demo
27
Perl Tutorial for Beginners
#!/usr/bin/perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Before: @foods\n";
#!/usr/bin/perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";
Merging Arrays
Because an array is just a comma-separated sequence of values, you can combine them together
as shown below −
28
Perl Tutorial for Beginners
Live Demo
#!/usr/bin/perl
@numbers = (1,3,(4,5,6));
#!/usr/bin/perl
@odd = (1,3,5);
@even = (2, 4, 6);
#!/usr/bin/perl
$var = (5,4,3,2,1)[4];
#!/usr/bin/perl
@list = (5,4,3,2,1)[1..3];
Perl - Hashes
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to
a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed
by the "key" associated with the value in curly brackets..
Here is a simple example of using the hash variables −
Live Demo
#!/usr/bin/perl
Creating Hashes
Hashes are created in one of the two following ways. In the first method, you assign a value to a
named key on a one-by-one basis −
$data{'John Paul'} = 45;
$data{'Lisa'} = 30;
$data{'Kumar'} = 40;
In the second case, you use a list, which is converted by taking individual pairs from the list: the
first element of the pair is used as the key, and the second, as the value. For example −
%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
For clarity, you can use => as an alias for , to indicate the key/value pairs as follows −
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
Here is one more variant of the above form, have a look at it, here all the keys have been preceded
by hyphen (-) and no quotation is required around them −
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
But it is important to note that there is a single word, i.e., without spaces keys have been used in
this form of hash formation and if you build-up your hash this way then keys will be accessed using
hyphen only as shown below.
$val = %data{-JohnPaul}
$val = %data{-Lisa}
30
Perl Tutorial for Beginners
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
Extracting Slices
You can extract slices of a hash just as you can extract slices from an array. You will need to use
@ prefix for the variable to store the returned value because they will be a list of values −
Live Demo
#!/uer/bin/perl
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
31
Perl Tutorial for Beginners
print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";
This will produce the following result −
Lisa
John Paul
Kumar
Similarly, you can use values function to get a list of all the values. This function has the following
syntax −
values %HASH
This function returns a normal array consisting of all the values of the named hash. Following is the
example −
Live Demo
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";
This will produce the following result −
30
45
40
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
if( exists($data{'Lisa'} ) ) {
print "Lisa is $data{'Lisa'} years old\n";
} else {
print "I don't know age of Lisa\n";
}
32
Perl Tutorial for Beginners
Here we have introduced the IF...ELSE statement, which we will study in a separate chapter. For
now you just assume that if( condition ) part will be executed only when the given condition is true
otherwise else part will be executed. So when we execute the above program, it produces the
following result because here the given condition exists($data{'Lisa'}returns true −
Lisa is 30 years old
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
33
Perl Tutorial for Beginners
delete $data{'Ali'};
@keys = keys %data;
$size = @keys;
print "3 - Hash size: is $size\n";
This will produce the following result −
1 - Hash size: is 3
2 - Hash size: is 4
3 - Hash size: is 3
Perl conditional statements helps in the decision making, which require that the programmer
specifies one or more conditions to be evaluated or tested by the program, along with a statement
or statements to be executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found in most of the
programming languages −
The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context
and all other values are true. Negation of a true value by ! or not returns a special false value.
Perl programming language provides the following types of conditional statements.
1 if statement
34
Perl Tutorial for Beginners
2 if...else statement
An if statement can be followed by an optional else statement.
3 if...elsif...else statement
An if statement can be followed by an optional elsif statement and then by an
optional else statement.
4 unless statement
An unless statement consists of a boolean expression followed by one or more
statements.
5 unless...else statement
An unless statement can be followed by an optional else statement.
6 unless...elsif..else statement
An unless statement can be followed by an optional elsif statement and then by an
optional else statement.
7 switch statement
With the latest versions of Perl, you can make use of the switch statement. which allows
a simple way of comparing a variable value against various conditions.
The ? : Operator
Let's check the conditional operator ? :which can be used to replace if...else statements. It has
the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is
evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated
and its value becomes the value of the expression. Below is a simple example making use of this
operator −
Live Demo
#!/usr/local/bin/perl
$name = "Ali";
$age = 10;
Perl - Loops
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
Perl programming language provides the following types of loop to handle the looping
requirements.
1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2 until loop
Repeats a statement or group of statements until a given condition becomes true. It tests
the condition before executing the loop body.
3 for loop
36
Perl Tutorial for Beginners
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
4 foreach loop
The foreach loop iterates over a normal list value and sets the variable VAR to be each
element of the list in turn.
5 do...while loop
Like a while statement, except that it tests the condition at the end of the loop body
6 nested loops
You can use one or more loop inside any another while, for or do..while loop.
1 next statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
2 last statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
3 continue statement
A continue BLOCK, it is always executed just before the conditional is about to be
evaluated again.
4 redo statement
The redo command restarts the loop block without evaluating the conditional again. The
continue block, if any, is not executed.
5 goto statement
Perl supports a goto command with three forms: goto label, goto expr, and goto &name.
37
Perl Tutorial for Beginners
for( ; ; ) {
printf "This loop will run forever.\n";
}
You can terminate the above infinite loop by pressing the Ctrl + C keys.
When the conditional expression is absent, it is assumed to be true. You may have an initialization
and increment expression, but as a programmer more commonly use the for (;;) construct to signify
an infinite loop.
Perl - Operators
What is an Operator?
Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and + is called operator. Perl language supports many operator types, but following is a
list of important and most frequently used operators −
• Arithmetic Operators
• Equality Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Logical Operators
• Quote-like Operators
• Miscellaneous Operators
Lets have a look at all the operators one by one.
1
+ ( Addition )
Adds values on either side of the operator
Example − $a + $b will give 30
38
Perl Tutorial for Beginners
2
- (Subtraction)
Subtracts right hand operand from left hand operand
Example − $a - $b will give -10
3
* (Multiplication)
Multiplies values on either side of the operator
Example − $a * $b will give 200
4
/ (Division)
Divides left hand operand by right hand operand
Example − $b / $a will give 2
5
% (Modulus)
Divides left hand operand by right hand operand and returns remainder
Example − $b % $a will give 0
6
** (Exponent)
Performs exponential (power) calculation on operators
Example − $a**$b will give 10 to the power 20
1
== (equal to)
Checks if the value of two operands are equal or not, if yes then condition becomes true.
Example − ($a == $b) is not true.
2
!= (not equal to)
Checks if the value of two operands are equal or not, if values are not equal then condition
becomes true.
Example − ($a != $b) is true.
39
Perl Tutorial for Beginners
3
<=>
Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on
whether the left argument is numerically less than, equal to, or greater than the right
argument.
Example − ($a <=> $b) returns -1.
4
> (greater than)
Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true.
Example − ($a > $b) is not true.
5
< (less than)
Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
Example − ($a < $b) is true.
6
>= (greater than or equal to)
Checks if the value of left operand is greater than or equal to the value of right operand,
if yes then condition becomes true.
Example − ($a >= $b) is not true.
7
<= (less than or equal to)
Checks if the value of left operand is less than or equal to the value of right operand, if
yes then condition becomes true.
Example − ($a <= $b) is true.
Below is a list of equity operators. Assume variable $a holds "abc" and variable $b holds "xyz" then,
lets check the following string equality operators −
Show Example
1
lt
Returns true if the left argument is stringwise less than the right argument.
Example − ($a lt $b) is true.
2
gt
Returns true if the left argument is stringwise greater than the right argument.
Example − ($a gt $b) is false.
40
Perl Tutorial for Beginners
3
le
Returns true if the left argument is stringwise less than or equal to the right argument.
Example − ($a le $b) is true.
4
ge
Returns true if the left argument is stringwise greater than or equal to the right argument.
Example − ($a ge $b) is false.
5
eq
Returns true if the left argument is stringwise equal to the right argument.
Example − ($a eq $b) is false.
6
ne
Returns true if the left argument is stringwise not equal to the right argument.
Example − ($a ne $b) is true.
7
cmp
Returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal
to, or greater than the right argument.
Example − ($a cmp $b) is -1.
1
=
Simple assignment operator, Assigns values from right side operands to left side operand
Example − $c = $a + $b will assigned value of $a + $b into $c
2
+=
Add AND assignment operator, It adds right operand to the left operand and assign the
result to left operand
Example − $c += $a is equivalent to $c = $c + $a
41
Perl Tutorial for Beginners
3
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and
assign the result to left operand
Example − $c -= $a is equivalent to $c = $c - $a
4
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and
assign the result to left operand
Example − $c *= $a is equivalent to $c = $c * $a
5
/=
Divide AND assignment operator, It divides left operand with the right operand and assign
the result to left operand
Example − $c /= $a is equivalent to $c = $c / $a
6
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the
result to left operand
Example − $c %= $a is equivalent to $c = $c % a
7
**=
Exponent AND assignment operator, Performs exponential (power) calculation on
operators and assign value to the left operand
Example − $c **= $a is equivalent to $c = $c ** $a
1
&
Binary AND Operator copies a bit to the result if it exists in both operands.
Example − ($a & $b) will give 12 which is 0000 1100
2
|
Binary OR Operator copies a bit if it exists in eather operand.
Example − ($a | $b) will give 61 which is 0011 1101
3
^
Binary XOR Operator copies the bit if it is set in one operand but not both.
Example − ($a ^ $b) will give 49 which is 0011 0001
4
~
Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.
Example − (~$a ) will give -61 which is 1100 0011 in 2's complement form due to a signed
binary number.
5
<<
Binary Left Shift Operator. The left operands value is moved left by the number of bits
specified by the right operand.
Example − $a << 2 will give 240 which is 1111 0000
6
>>
Binary Right Shift Operator. The left operands value is moved right by the number of bits
specified by the right operand.
Example − $a >> 2 will give 15 which is 0000 1111
43
Perl Tutorial for Beginners
1
and
Called Logical AND operator. If both the operands are true then then condition becomes
true.
Example − ($a and $b) is false.
2
&&
C-style Logical AND operator copies a bit to the result if it exists in both operands.
Example − ($a && $b) is false.
3
or
Called Logical OR Operator. If any of the two operands are non zero then then condition
becomes true.
Example − ($a or $b) is true.
4
||
C-style Logical OR operator copies a bit if it exists in eather operand.
Example − ($a || $b) is true.
5
not
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a
condition is true then Logical NOT operator will make false.
Example − not($a and $b) is true.
Quote-like Operators
There are following Quote-like operators supported by Perl language. In the following table, a {}
represents any pair of delimiters you choose.
Show Example
1
q{ }
Encloses a string with-in single quotes
Example − q{abcd} gives 'abcd'
2
qq{ }
Encloses a string with-in double quotes
44
Perl Tutorial for Beginners
3
qx{ }
Encloses a string with-in invert quotes
Example − qx{abcd} gives `abcd`
Miscellaneous Operators
There are following miscellaneous operators supported by Perl language. Assume variable a holds
10 and variable b holds 20 then −
Show Example
1
.
Binary operator dot (.) concatenates two strings.
Example − If $a = "abc", $b = "def" then $a.$b will give "abcdef"
2
x
The repetition operator x returns a string consisting of the left operand repeated the
number of times specified by the right operand.
Example − ('-' x 3) will give ---.
3
..
The range operator .. returns a list of values counting (up by ones) from the left value to
the right value
Example − (2..5) will give (2, 3, 4, 5)
4
++
Auto Increment operator increases integer value by one
Example − $a++ will give 11
5
--
Auto Decrement operator decreases integer value by one
Example − $a-- will give 9
6
->
45
Perl Tutorial for Beginners
The arrow operator is mostly used in dereferencing a method or variable from an object
or a class name
Example − $obj->$a is an example to access variable $a from object $obj.
46
Perl Tutorial for Beginners
#!/usr/local/bin/perl
@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
print "$mday $months[$mon] $days[$wday]\n";
When the above code is executed, it produces the following result −
16 Feb Sat
If you will use localtime() function in scalar context, then it will return date and time from the current
time zone set in the system. Try the following example to print current date and time in full format
−
Live Demo
#!/usr/local/bin/perl
$datestring = localtime();
print "Local date and time $datestring\n";
When the above code is executed, it produces the following result −
Local date and time Sat Feb 16 06:50:45 2013
GMT Time
The function gmtime() works just like localtime() function but the returned values are localized for
the standard Greenwich time zone. When called in list context, $isdst, the last value returned by
gmtime, is always 0. There is no Daylight Saving Time in GMT.
You should make a note on the fact that localtime() will return the current local time on the machine
that runs the script and gmtime() will return the universal Greenwich Mean Time, or GMT (or UTC).
Try the following example to print the current date and time but on GMT scale −
Live Demo
#!/usr/local/bin/perl
$datestring = gmtime();
print "GMT date and time $datestring\n";
When the above code is executed, it produces the following result −
GMT date and time Sat Feb 16 13:50:45 2013
47
Perl Tutorial for Beginners
#!/usr/local/bin/perl
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
Epoch time
You can use the time() function to get epoch time, i.e., the numbers of seconds that have elapsed
since a given date, in Unix is January 1, 1970.
Live Demo
#!/usr/local/bin/perl
$epoc = time();
#!/usr/local/bin/perl
$datestring = localtime();
print "Current date and time $datestring\n";
$epoc = time();
$epoc = $epoc - 24 * 60 * 60; # one day before of current date.
$datestring = localtime($epoc);
print "Yesterday's date and time $datestring\n";
When the above code is executed, it produces the following result −
Current date and time Tue Jun 5 05:54:43 2018
Yesterday's date and time Mon Jun 4 05:54:43 2018
48
Perl Tutorial for Beginners
49
Perl Tutorial for Beginners
%M Minute (00-59) 55
%p AM or PM designation PM
%S Second (00-61) 02
50
Perl Tutorial for Beginners
%Y Year 2001
%z +100
ISO 8601 offset from UTC in timezone (1 minute = 1, 1
hour = 100)
If timezone cannot be termined, no characters
%Z CDT
Timezone name or abbreviation *
If timezone cannot be termined, no characters
%% A % sign %
#!/usr/local/bin/perl
use POSIX qw(strftime);
Perl - Subroutines
A Perl subroutine or function is a group of statements that together performs a task. You can divide
up your code into separate subroutines. How you divide up your code among different subroutines
is up to you, but logically the division usually is so each function performs a specific task.
Perl uses the terms subroutine, method and function interchangeably.
51
Perl Tutorial for Beginners
#!/usr/bin/perl
# Function definition
sub Hello {
print "Hello, World!\n";
}
# Function call
Hello();
When above program is executed, it produces the following result −
Hello, World!
#!/usr/bin/perl
# Function definition
sub Average {
# get total number of arguments passed.
$n = scalar(@_);
52
Perl Tutorial for Beginners
$sum = 0;
# Function call
Average(10, 20, 30);
When above program is executed, it produces the following result −
Average for the given numbers : 20
#!/usr/bin/perl
# Function definition
sub PrintList {
my @list = @_;
print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);
#!/usr/bin/perl
# Function definition
sub PrintHash {
my (%hash) = @_;
53
Perl Tutorial for Beginners
#!/usr/bin/perl
# Function definition
sub Average {
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n";
When above program is executed, it produces the following result −
Average for the given numbers : 20
54
Perl Tutorial for Beginners
#!/usr/bin/perl
# Global variable
$string = "Hello, World!";
# Function definition
sub PrintHello {
# Private variable for PrintHello function
my $string;
$string = "Hello, Perl!";
print "Inside the function $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";
When above program is executed, it produces the following result −
Inside the function Hello, Perl!
Outside the function Hello, World!
Live Demo
#!/usr/bin/perl
# Global variable
$string = "Hello, World!";
sub PrintHello {
# Private variable for PrintHello function
local $string;
$string = "Hello, Perl!";
PrintMe();
print "Inside the function PrintHello $string\n";
}
sub PrintMe {
print "Inside the function PrintMe $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";
When above program is executed, it produces the following result −
Inside the function PrintMe Hello, Perl!
Inside the function PrintHello Hello, Perl!
Outside the function Hello, World!
#!/usr/bin/perl
sub PrintCount {
state $count = 0; # initial value
for (1..5) {
PrintCount();
}
When above program is executed, it produces the following result −
Value of counter is 0
56
Perl Tutorial for Beginners
Value of counter is 1
Value of counter is 2
Value of counter is 3
Value of counter is 4
Prior to Perl 5.10, you would have to write it like this −
Live Demo
#!/usr/bin/perl
{
my $count = 0; # initial value
sub PrintCount {
print "Value of counter is $count\n";
$count++;
}
}
for (1..5) {
PrintCount();
}
Perl - References
A Perl reference is a scalar data type that holds the location of another value which could be scalar,
arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can
be used.
You can construct lists containing references to other lists, which can contain references to hashes,
and so on. This is how the nested data structures are built in Perl.
Create References
It is easy to create a reference for any variable, subroutine or value by prefixing it with a backslash
as follows −
57
Perl Tutorial for Beginners
$scalarref = \$foo;
$arrayref = \@ARGV;
$hashref = \%ENV;
$coderef = \&handler;
$globref = \*foo;
You cannot create a reference on an I/O handle (filehandle or dirhandle) using the backslash
operator but a reference to an anonymous array can be created using the square brackets as
follows −
$arrayref = [1, 2, ['a', 'b', 'c']];
Similar way you can create a reference to an anonymous hash using the curly brackets as follows
−
$hashref = {
'Adam' => 'Eve',
'Clyde' => 'Bonnie',
};
A reference to an anonymous subroutine can be created by using sub without a subname as follows
−
$coderef = sub { print "Boink!\n" };
Dereferencing
Dereferencing returns the value from a reference point to the location. To dereference a reference
simply use $, @ or % as prefix of the reference variable depending on whether the reference is
pointing to a scalar, array, or hash. Following is the example to explain the concept −
Live Demo
#!/usr/bin/perl
$var = 10;
58
Perl Tutorial for Beginners
Value of 10 is : 10
Value of 1 2 3 is : 123
Value of %var is : key220key110
If you are not sure about a variable type, then its easy to know its type using ref, which returns one
of the following strings if its argument is a reference. Otherwise, it returns false −
SCALAR
ARRAY
HASH
CODE
GLOB
REF
Let's try the following example −
Live Demo
#!/usr/bin/perl
$var = 10;
$r = \$var;
print "Reference type in r : ", ref($r), "\n";
Circular References
A circular reference occurs when two references contain a reference to each other. You have to be
careful while creating references otherwise a circular reference can lead to memory leaks.
Following is an example −
Live Demo
#!/usr/bin/perl
my $foo = 100;
$foo = \$foo;
59
Perl Tutorial for Beginners
References to Functions
This might happen if you need to create a signal handler so you can produce a reference to a
function by preceding that function name with \& and to dereference that reference you simply need
to prefix reference variable using ampersand &. Following is an example −
Live Demo
#!/usr/bin/perl
# Function definition
sub PrintHash {
my (%hash) = @_;
Perl - Formats
Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl,
you have to define a format first and then you can use that format to write formatted data.
Define a Format
Following is the syntax to define a Perl format −
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.
Here FormatName represents the name of the format. The fieldline is the specific way, the data
should be formatted. The values lines represent the values that will be entered into the field line.
You end the format with a single period.
60
Perl Tutorial for Beginners
Next fieldline can contain any text or fieldholders. The fieldholders hold space for data that will be
placed there at a later date. A fieldholder has the format −
@<<<<
This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs
to know the number of spaces in the field. Other field holders include −
@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder
An example format would be −
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
In this example, $name would be written as left justify within 22 character spaces and after that age
will be written in two spaces.
#!/usr/bin/perl
format EMPLOYEE =
===================================
61
Perl Tutorial for Beginners
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
$i = 0;
foreach (@n) {
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
When executed, this will produce the following result −
===================================
Ali 20
2000.00
===================================
===================================
Raza 30
2500.00
===================================
===================================
Jaffer 40
4000.00
===================================
#!/usr/bin/perl
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
62
Perl Tutorial for Beginners
format EMPLOYEE_TOP =
===================================
Name Age
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
$^ = EMPLOYEE_TOP;
$i = 0;
foreach (@n) {
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
Now your report will look like −
===================================
Name Age
===================================
===================================
Ali 20
2000.00
===================================
===================================
Raza 30
2500.00
===================================
===================================
Jaffer 40
4000.00
===================================
Define a Pagination
What about if your report is taking more than one page? You have a solution for that, simply
use $% or $FORMAT_PAGE_NUMBER vairable along with header as follows −
format EMPLOYEE_TOP =
===================================
Name Age Page @<
$%
===================================
.
Now your output will look like as follows −
===================================
63
Perl Tutorial for Beginners
64
Perl Tutorial for Beginners
Open Function
Following is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file
has to be opend in read-only mode.
open(DATA, "<file.txt");
Here DATA is the file handle, which will be used to read the file. Here is the example, which will
open a file and will print its content over the screen.
#!/usr/bin/perl
while(<DATA>) {
print "$_";
}
Following is the syntax to open file.txt in writing mode. Here less than > sign indicates that file has
to be opend in the writing mode.
open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!";
This example actually truncates (empties) the file before opening it for writing, which may not be
the desired effect. If you want to open a file for reading and writing, you can put a plus sign before
the > or < characters.
For example, to open a file for updating without truncating it −
open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!";
To truncate the file first −
open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!";
You can open a file in the append mode. In this mode, writing point will be set to the end of the file.
open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";
A double >> opens the file for appending, placing the file pointer at the end, so that you can
immediately start appending information. However, you can't read from it unless you also place a
plus sign in front of it −
open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";
Following is the table, which gives the possible values of different modes
65
Perl Tutorial for Beginners
1
< or r
Read Only Access
2
> or w
Creates, Writes, and Truncates
3
>> or a
Writes, Appends, and Creates
4
+< or r+
Reads and Writes
5
+> or w+
Reads, Writes, Creates, and Truncates
6
+>> or a+
Reads, Writes, Appends, and Creates
Sysopen Function
The sysopen function is similar to the main open function, except that it uses the
system open() function, using the parameters supplied to it as the parameters for the system
function −
For example, to open a file for updating, emulating the +<filename format from open −
sysopen(DATA, "file.txt", O_RDWR);
Or to truncate the file before updating −
sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );
You can use O_CREAT to create a new file and O_WRONLY- to open file in write only mode and
O_RDONLY - to open file in read only mode.
The PERMS argument specifies the file permissions for the file specified, if it has to be created. By
default it takes 0x666.
Following is the table, which gives the possible values of MODE.
66
Perl Tutorial for Beginners
1
O_RDWR
Read and Write
2
O_RDONLY
Read Only
3
O_WRONLY
Write Only
4
O_CREAT
Create the file
5
O_APPEND
Append the file
6
O_TRUNC
Truncate the file
7
O_EXCL
Stops if file already exists
8
O_NONBLOCK
Non-Blocking usability
Close Function
To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use
the close function. This flushes the filehandle's buffers and closes the system's file descriptor.
close FILEHANDLE
close
If no FILEHANDLE is specified, then it closes the currently selected filehandle. It returns true only
if it could successfully flush the buffers and close the file.
close(DATA) || die "Couldn't close file properly";
67
Perl Tutorial for Beginners
getc Function
The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is
specified −
getc FILEHANDLE
getc
If there was an error, or the filehandle is at end of file, then undef is returned instead.
read Function
The read function reads a block of information from the buffered filehandle: This function is used to
read binary data from the file.
read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH
The length of the data read is defined by LENGTH, and the data is placed at the start of SCALAR
if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function
returns the number of bytes read on success, zero at end of file, or undef if there was an error.
print Function
For all the different methods used for reading information from filehandles, the main function for
writing information back is the print function.
print FILEHANDLE LIST
print LIST
print
The print function prints the evaluated value of LIST to FILEHANDLE, or to the current output
filehandle (STDOUT by default). For example −
print "Hello World!\n";
68
Perl Tutorial for Beginners
Copying Files
Here is the example, which opens an existing file file1.txt and read it line by line and generate
another copy file file2.txt.
#!/usr/bin/perl
Renaming a file
Here is an example, which shows how we can rename a file file1.txt to file2.txt. Assuming file is
available in /usr/test directory.
#!/usr/bin/perl
unlink ("/usr/test/file1.txt");
tell Function
The first requirement is to find your position within a file, which you do using the tell function −
tell FILEHANDLE
tell
This returns the position of the file pointer, in bytes, within FILEHANDLE if specified, or the current
default selected filehandle if none is specified.
69
Perl Tutorial for Beginners
seek Function
The seek function positions the file pointer to the specified number of bytes within a file −
seek FILEHANDLE, POSITION, WHENCE
The function uses the fseek system function, and you have the same ability to position relative to
three different points: the start, the end, and the current position. You do this by specifying a value
for WHENCE.
Zero sets the positioning relative to the start of the file. For example, the line sets the file pointer to
the 256th byte in the file.
seek DATA, 256, 0;
File Information
You can test certain features very quickly within Perl using a series of test operators known
collectively as -X tests. For example, to perform a quick test of the various permissions on a file,
you might use a script like this −
#/usr/bin/perl
my $file = "/usr/test/file1.txt";
my (@description, $size);
if (-e $file) {
push @description, 'binary' if (-B _);
push @description, 'a socket' if (-S _);
push @description, 'a text file' if (-T _);
push @description, 'a block special file' if (-b _);
push @description, 'a character special file' if (-c _);
push @description, 'a directory' if (-d _);
push @description, 'executable' if (-x _);
push @description, (($size = -s _)) ? "$size bytes" : 'empty';
print "$file is ", join(', ',@description),"\n";
}
Here is the list of features, which you can check for a file or directory −
1
-A
Script start time minus file last access time, in days.
2
-B
Is it a binary file?
3
-C
Script start time minus file last inode change time, in days.
70
Perl Tutorial for Beginners
3
-M
Script start time minus file modification time, in days.
4
-O
Is the file owned by the real user ID?
5
-R
Is the file readable by the real user ID or real group?
6
-S
Is the file a socket?
7
-T
Is it a text file?
8
-W
Is the file writable by the real user ID or real group?
9
-X
Is the file executable by the real user ID or real group?
10
-b
Is it a block special file?
11
-c
Is it a character special file?
12
-d
Is the file a directory?
13
-e
Does the file exist?
14
-f
Is it a plain file?
71
Perl Tutorial for Beginners
15
-g
Does the file have the setgid bit set?
16
-k
Does the file have the sticky bit set?
17
-l
Is the file a symbolic link?
18
-o
Is the file owned by the effective user ID?
19
-p
Is the file a named pipe?
20
-r
Is the file readable by the effective user or group ID?
21
-s
Returns the size of the file, zero size = empty file.
22
-t
Is the filehandle opened by a TTY (terminal)?
23
-u
Does the file have the setuid bit set?
24
-w
Is the file writable by the effective user or group ID?
25
-x
Is the file executable by the effective user or group ID?
26
-z
Is the file size zero?
72
Perl Tutorial for Beginners
Perl - Directories
Following are the standard functions used to play with directories.
opendir DIRHANDLE, EXPR # To open a directory
readdir DIRHANDLE # To read a directory
rewinddir DIRHANDLE # Positioning pointer to the begining
telldir DIRHANDLE # Returns current position of the dir
seekdir DIRHANDLE, POS # Pointing pointer to POS inside dir
closedir DIRHANDLE # Closing a directory.
foreach (@files ) {
print $_ . "\n";
}
foreach (@files ) {
print $_ . "\n";
}
foreach (@files ) {
print $_ . "\n";
}
Here is another example, which opens a directory and list out all the files available inside this
directory.
#!/usr/bin/perl
$dir = "/tmp/perl";
Remove a directory
You can use rmdir function to remove a directory. You will need to have the required permission
to remove a directory. Additionally this directory should be empty before you try to remove it.
#!/usr/bin/perl
$dir = "/tmp/perl";
Change a Directory
You can use chdir function to change a directory and go to a new location. You will need to have
the required permission to change a directory and go inside the new directory.
#!/usr/bin/perl
$dir = "/home";
# This changes perl directory and moves you inside /home directory.
chdir( $dir ) or die "Couldn't go inside $dir directory, $!";
print "Your new location is $dir\n";
74
Perl Tutorial for Beginners
The if statement
The if statement is the obvious choice when you need to check the return value from a statement;
for example −
if(open(DATA, $file)) {
...
} else {
die "Error: Couldn't open the file - $!";
}
Here variable $! returns the actual error message. Alternatively, we can reduce the statement to
one line in situations where it makes sense to do so; for example −
open(DATA, $file) || die "Error: Couldn't open the file $!";
75
Perl Tutorial for Beginners
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;
sub function {
warn "Error in module!";
}
1;
When called from a script like below −
use T;
function();
It will produce the following result −
Error in module! at T.pm line 9.
This is more or less what you might expected, but not necessarily what you want. From a module
programmer's perspective, the information is useful because it helps to point to a bug within the
module itself. For an end-user, the information provided is fairly useless, and for all but the
hardened programmer, it is completely pointless.
76
Perl Tutorial for Beginners
The solution for such problems is the Carp module, which provides a simplified method for reporting
errors within modules that return information about the calling script. The Carp module provides
four functions: carp, cluck, croak, and confess. These functions are discussed below.
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;
sub function {
carp "Error in module!";
}
1;
When called from a script like below −
use T;
function();
It will produce the following result −
Error in module! at test.pl line 4
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp qw(cluck);
sub function {
cluck "Error in module!";
}
1;
When called from a script like below −
use T;
function();
It will produce the following result −
Error in module! at T.pm line 9
T::function() called at test.pl line 4
77
Perl Tutorial for Beginners
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;
sub function {
croak "Error in module!";
}
1;
When called from a script like below −
use T;
function();
It will produce the following result −
Error in module! at test.pl line 4
As with carp, the same basic rules apply regarding the including of line and file information
according to the warn and die functions.
require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;
sub function {
confess "Error in module!";
}
1;
When called from a script like below −
use T;
function();
It will produce the following result −
Error in module! at T.pm line 9
T::function() called at test.pl line 4
78
Perl Tutorial for Beginners
#!/usr/bin/perl
foreach ('hickory','dickory','doc') {
print $_;
print "\n";
}
When executed, this will produce the following result −
hickory
dickory
doc
Again, let's check the same example without using $_ variable explicitly −
Live Demo
#!/usr/bin/perl
foreach ('hickory','dickory','doc') {
print;
print "\n";
}
When executed, this will also produce the following result −
hickory
dickory
doc
The first time the loop is executed, "hickory" is printed. The second time around, "dickory" is printed,
and the third time, "doc" is printed. That's because in each iteration of the loop, the current string
is placed in $_, and is used by default by print. Here are the places where Perl will assume $_ even
if you don't specify it −
• Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -
t, which defaults to STDIN.
• Various list functions like print and unlink.
• The pattern-matching operations m//, s///, and tr/// when used without an =~ operator.
• The default iterator variable in a foreach loop if no other variable is supplied.
79
Perl Tutorial for Beginners
$_
The default input and pattern-searching space.
$ARG
$.
The current input line number of the last filehandle
that was read. An explicit close on the filehandle
resets the line number.
$NR
$/
The input record separator; newline by default. If set
to the null string, it treats blank lines as delimiters.
$RS
$,
The output field separator for the print operator.
$OFS
80
Perl Tutorial for Beginners
$ORS
$"
Like "$," except that it applies to list values
interpolated into a double-quoted string (or similar
interpreted string). Default is a space.
$LIST_SEPARATOR
$;
The subscript separator for multidimensional array
emulation. Default is "\034".
$SUBSCRIPT_SEPARATOR
$^L
What a format outputs to perform a formfeed. Default
is "\f".
$FORMAT_FORMFEED
$:
The current set of characters after which a string
may be broken to fill continuation fields (starting with
^) in a format. Default is "\n"".
$FORMAT_LINE_BREAK_CHARACTERS
$^A
The current value of the write accumulator for format
lines.
$ACCUMULATOR
$#
Contains the output format for printed numbers
(deprecated).
$OFMT
$?
The status returned by the last pipe close, backtick
(``) command, or system operator.
$CHILD_ERROR
81
Perl Tutorial for Beginners
$@
The Perl syntax error message from the last eval
command.
$EVAL_ERROR
$$
The pid of the Perl process running this script.
$PROCESS_ID or $PID
$<
The real user ID (uid) of this process.
$REAL_USER_ID or $UID
$>
The effective user ID of this process.
$EFFECTIVE_USER_ID or $EUID
$(
The real group ID (gid) of this process.
$REAL_GROUP_ID or $GID
$)
The effective gid of this process.
$EFFECTIVE_GROUP_ID or $EGID
$PROGRAM_NAME
82
Perl Tutorial for Beginners
$PERL_VERSION
$^D
The current value of the debugging flags.
$DEBUGGING
$^E
Extended error message on some platforms.
$EXTENDED_OS_ERROR
$^F
The maximum system file descriptor, ordinarily 2.
$SYSTEM_FD_MAX
$^I
The current value of the inplace-edit extension. Use
undef to disable inplace editing.
$INPLACE_EDIT
$^O
Contains the name of the operating system that the
current Perl binary was compiled for.
$OSNAME
$^P
The internal flag that the debugger clears so that it
doesn't debug itself.
$PERLDB
83
Perl Tutorial for Beginners
$^T
The time at which the script began running, in
seconds since the epoch.
$BASETIME
$^W
The current value of the warning switch, either true
or false.
$WARNING
$^X
The name that the Perl binary itself was executed as.
$EXECUTABLE_NAME
@INC The array containing the list of places to look for Perl scripts to be
evaluated by the do, require, or use constructs.
@F The array into which the input lines are split when the -a command-
line switch is given.
%SIG The hash used to set signal handlers for various signals.
84
Perl Tutorial for Beginners
DATA The special filehandle that refers to anything following the __END__ token in the
file containing the script. Or, the special filehandle for anything following the
__DATA__ token in a required file, as long as you're reading data in the same
package __DATA__ was found in.
_ The special filehandle used to cache the information from the last stat, lstat, or file
(underscore) test operator.
__FILE__ Represents the filename at the point in your program where it's
used. Not interpolated into strings.
__LINE__ Represents the current line number. Not interpolated into strings.
85
Perl Tutorial for Beginners
$&
The string matched by the last successful pattern match.
$MATCH
$`
The string preceding whatever was matched by the last successful
pattern match.
$PREMATCH
$'
The string following whatever was matched by the last successful
pattern match.
$POSTMATCH
$+ The last bracket matched by the last search pattern. This is useful if
you don't know which of a set of alternative patterns was matched.
For example : /Version: (.*)|Revision: (.*)/ && ($rev = $+);
$LAST_PAREN_MATCH
$%
The current page number of the currently selected output
channel.
$FORMAT_PAGE_NUMBER
$=
The current page length (printable lines) of the currently
selected output channel. Default is 60.
$FORMAT_LINES_PER_PAGE
$-
86
Perl Tutorial for Beginners
$FORMAT_LINES_LEFT The number of lines left on the page of the currently selected
output channel.
$~
The name of the current report format for the currently selected
output channel. Default is the name of the filehandle.
$FORMAT_NAME
• 4-column indent.
• Opening curly on same line as keyword, if possible, otherwise line up.
• Space before the opening curly of a multi-line BLOCK.
• One-line BLOCK may be put on one line, including curlies.
• No space before the semicolon.
• Semicolon omitted in "short" one-line BLOCK.
• Space around most operators.
• Space around a "complex" subscript (inside brackets).
• Blank lines between chunks that do different things.
• Uncuddled elses.
• No space between function name and its opening parenthesis.
• Space after each comma.
• Long lines broken after an operator (except and and or).
• Space after last parenthesis matching on current line.
• Line up corresponding items vertically.
• Omit redundant punctuation as long as clarity doesn't suffer.
87
Perl Tutorial for Beginners
Here are some other more substantive style issues to think about: Just because you CAN do
something a particular way doesn't mean that you SHOULD do it that way. Perl is designed to give
you several ways to do anything, so consider picking the most readable one. For instance −
open(FOO,$foo) || die "Can't open $foo: $!";
Is better than −
die "Can't open $foo: $!" unless open(FOO,$foo);
Because the second way hides the main point of the statement in a modifier. On the other hand,
print "Starting analysis\n" if $verbose;
Is better than −
$verbose && print "Starting analysis\n";
Because the main point isn't whether the user typed -v or not.
Don't go through silly contortions to exit a loop at the top or the bottom, when Perl provides the last
operator so you can exit in the middle. Just "outdent" it a little to make it more visible −
LINE:
for (;;) {
statements;
last LINE if $foo;
next LINE if /^#/;
statements;
}
Let's see few more important points −
• Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop
breaks. See the previous example.
• Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return
values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the
system() function instead.
• For portability, when using features that may not be implemented on every machine, test the construct in
an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you
can test $] ($PERL_VERSION in English) to see if it will be there. The Config module will also let you
interrogate values determined by the Configure program when Perl was installed.
• Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem.
• While short identifiers like $gotit are probably ok, use underscores to separate words in longer identifiers.
It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native
speakers of English. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS.
• Package names are sometimes an exception to this rule. Perl informally reserves lowercase module
names for "pragma" modules like integer and strict. Other modules should begin with a capital letter and
use mixed case, but probably without underscores due to limitations in primitive file systems'
representations of module names as files that must fit into a few sparse bytes.
• If you have a really hairy regular expression, use the /x modifier and put in some whitespace to make it
look a little less like line noise. Don't use slash as a delimiter when your regexp has slashes or
backslashes.
• Always check the return codes of system calls. Good error messages should go to STDERR, include
which program caused the problem, what the failed system call and arguments were, and (VERY
IMPORTANT) should contain the standard system error message for what went wrong. Here's a simple
but sufficient example −
88
Perl Tutorial for Beginners
#!/usr/bin/perl
$bar = "foo";
if ($bar =~ /foo/) {
print "Second time is matching\n";
} else {
print "Second time is not matching\n";
}
When above program is executed, it produces the following result −
First time is matching
89
Perl Tutorial for Beginners
$bar = "foo";
if ($bar =~ m{foo}) {
print "Second time is matching\n";
} else {
print "Second time is not matching\n";
}
You can omit m from m// if the delimiters are forward slashes, but for all other delimiters you must
use the m prefix.
Note that the entire match expression, that is the expression on the left of =~ or !~ and the match
operator, returns true (in a scalar context) if the expression matches. Therefore the statement −
$true = ($foo =~ m/foo/);
will set $true to 1 if $foo matches the regex, or 0 if the match fails. In a list context, the match returns
the contents of any grouped expressions. For example, when extracting the hours, minutes, and
seconds from a time string, we can use −
my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);
1
i
Makes the match case insensitive.
2
m
Specifies that if the string has newline or carriage return characters, the ^ and $ operators
will now match against a newline boundary, instead of a string boundary.
3
o
90
Perl Tutorial for Beginners
4
s
Allows use of . to match a newline character.
5
x
Allows you to use white space in the expression for clarity.
6
g
Globally finds all matches.
7
cg
Allows the search to continue even after a global match fails.
#!/usr/bin/perl
foreach (@list) {
$first = $1 if /(foo.*?)/;
$last = $1 if /(foo.*)/;
}
print "First: $first, Last: $last\n";
When above program is executed, it produces the following result −
First: foo, Last: footbrdige
91
Perl Tutorial for Beginners
#!/usr/bin/perl
#/user/bin/perl
print "$string\n";
When above program is executed, it produces the following result −
The dog sat on the mat
1
i
Makes the match case insensitive.
2
m
Specifies that if the string has newline or carriage return characters, the ^ and $ operators
will now match against a newline boundary, instead of a string boundary.
92
Perl Tutorial for Beginners
3
o
Evaluates the expression only once.
4
s
Allows use of . to match a newline character.
5
x
Allows you to use white space in the expression for clarity.
6
g
Replaces all occurrences of the found expression with the replacement text.
7
e
Evaluates the replacement as if it were a Perl statement, and uses its return value as the
replacement text.
#/user/bin/perl
print "$string\n";
When above program is executed, it produces the following result −
The cot sot on the mot.
Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter
or numerical value. To change the case of the string, you might use the following syntax in place
of the uc function.
$string =~ tr/a-z/A-Z/;
93
Perl Tutorial for Beginners
1
c
Complements SEARCHLIST.
2
d
Deletes found but unreplaced characters.
3
s
Squashes duplicate replaced characters.
The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding
entry in REPLACEMENTLIST. For example −
Live Demo
#!/usr/bin/perl
print "$string\n";
When above program is executed, it produces the following result −
b b b.
The last modifier, /s, removes the duplicate sequences of characters that were replaced, so −
Live Demo
#!/usr/bin/perl
$string = 'food';
$string = 'food';
$string =~ tr/a-z/a-z/s;
print "$string\n";
When above program is executed, it produces the following result −
fod
94
Perl Tutorial for Beginners
1
^
Matches beginning of line.
2
$
Matches end of line.
3
.
Matches any single character except newline. Using m option allows it to match newline
as well.
4
[...]
Matches any single character in brackets.
5
[^...]
Matches any single character not in brackets.
6
*
Matches 0 or more occurrences of preceding expression.
7
+
Matches 1 or more occurrence of preceding expression.
8
?
Matches 0 or 1 occurrence of preceding expression.
9
{ n}
Matches exactly n number of occurrences of preceding expression.
10
{ n,}
Matches n or more occurrences of preceding expression.
95
Perl Tutorial for Beginners
11
{ n, m}
Matches at least n and at most m occurrences of preceding expression.
12
a| b
Matches either a or b.
13
\w
Matches word characters.
14
\W
Matches nonword characters.
15
\s
Matches whitespace. Equivalent to [\t\n\r\f].
16
\S
Matches nonwhitespace.
17
\d
Matches digits. Equivalent to [0-9].
18
\D
Matches nondigits.
19
\A
Matches beginning of string.
20
\Z
Matches end of string. If a newline exists, it matches just before newline.
21
\z
Matches end of string.
22
\G
Matches point where last match finished.
96
Perl Tutorial for Beginners
23
\b
Matches word boundaries when outside brackets. Matches backspace (0x08) when inside
brackets.
24
\B
Matches nonword boundaries.
25
\n, \t, etc.
Matches newlines, carriage returns, tabs, etc.
26
\1...\9
Matches nth grouped subexpression.
27
\10
Matches nth grouped subexpression if it matched already. Otherwise refers to the octal
representation of a character code.
28
[aeiou]
Matches a single character in the given set
29
[^aeiou]
Matches a single character outside the given set
The ^ metacharacter matches the beginning of the string and the $ metasymbol matches the end
of the string. Here are some brief examples.
# nothing in the string (start and end are adjacent)
/^$/
97
Perl Tutorial for Beginners
Live Demo
#!/usr/bin/perl
Matching Boundaries
The \b matches at any word boundary, as defined by the difference between the \w class and the
\W class. Because \w includes the characters for a word, and \W the opposite, this normally means
the termination of a word. The \B assertion matches any position that is not a word boundary. For
example −
/\bcat\b/ # Matches 'the cat sat' but not 'cat on the mat'
/\Bcat\B/ # Matches 'verification' but not 'the cat on the mat'
/\bcat\B/ # Matches 'catatonic' but not 'polecat'
/\Bcat\b/ # Matches 'polecat' but not 'catatonic'
Selecting Alternatives
The | character is just like the standard or bitwise OR within Perl. It specifies alternate matches
within a regular expression or group. For example, to match "cat" or "dog" in an expression, you
might use this −
if ($string =~ /cat|dog/)
You can group individual elements of an expression together in order to support complex matches.
Searching for two people’s names could be achieved with two separate tests, like this −
if (($string =~ /Martin Brown/) || ($string =~ /Sharon Brown/))
Grouping Matching
From a regular-expression point of view, there is no difference between except, perhaps, that the
former is slightly clearer.
$string =~ /(\S+)\s+(\S+)/;
and
$string =~ /\S+\s+\S+/;
98
Perl Tutorial for Beginners
However, the benefit of grouping is that it allows us to extract a sequence from a regular expression.
Groupings are returned as a list in the order in which they appear in the original. For example, in
the following fragment we have pulled out the hours, minutes, and seconds from a string.
my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);
As well as this direct method, matched groups are also available within the special $x variables,
where x is the number of the group within the regular expression. We could therefore rewrite the
preceding example as follows −
Live Demo
#!/usr/bin/perl
$time = "12:05:30";
$time =~ m/(\d+):(\d+):(\d+)/;
my ($hours, $minutes, $seconds) = ($1, $2, $3);
#!/usr/bin/perl
$date = '03/26/1999';
$date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#;
print "$date\n";
When above program is executed, it produces the following result −
1999/03/26
The \G Assertion
The \G assertion allows you to continue searching from the point where the last match occurred.
For example, in the following code, we have used \G so that we can search to the correct position
and then extract some information, without having to create a more complex, single regular
expression −
Live Demo
#!/usr/bin/perl
$string =~ /:\s+/g;
($time) = ($string =~ /\G(\d+:\d+:\d+)/);
$string =~ /.+\s+/g;
99
Perl Tutorial for Beginners
Regular-expression Examples
Literal Characters
1
Perl
Match "Perl".
Character Classes
1
[Pp]ython
Matches "Python" or "python"
2
rub[ye]
Matches "ruby" or "rube"
3
[aeiou]
Matches any one lowercase vowel
4
[0-9]
Matches any digit; same as [0123456789]
5
[a-z]
Matches any lowercase ASCII letter
100
Perl Tutorial for Beginners
6
[A-Z]
Matches any uppercase ASCII letter
7
[a-zA-Z0-9]
Matches any of the above
8
[^aeiou]
Matches anything other than a lowercase vowel
9
[^0-9]
Matches anything other than a digit
1
.
Matches any character except newline
2
\d
Matches a digit: [0-9]
3
\D
Matches a nondigit: [^0-9]
4
\s
Matches a whitespace character: [ \t\r\n\f]
5
\S
Matches nonwhitespace: [^ \t\r\n\f]
6
\w
Matches a single word character: [A-Za-z0-9_]
7
\W
101
Perl Tutorial for Beginners
Repetition Cases
1
ruby?
Matches "rub" or "ruby": the y is optional
2
ruby*
Matches "rub" plus 0 or more ys
3
ruby+
Matches "rub" plus 1 or more ys
4
\d{3}
Matches exactly 3 digits
5
\d{3,}
Matches 3 or more digits
6.
\d{3,5}
Matches 3, 4, or 5 digits
Nongreedy Repetition
This matches the smallest number of repetitions −
1
<.*>
Greedy repetition: matches "<python>perl>"
2
<.*?>
Nongreedy: matches "<python>" in "<python>perl>"
102
Perl Tutorial for Beginners
1
\D\d+
No group: + repeats \d
2
(\D\d)+
Grouped: + repeats \D\d pair
3
([Pp]ython(, )?)+
Match "Python", "Python, python, python", etc.
Backreferences
This matches a previously matched group again −
1
([Pp])ython&\1ails
Matches python&pails or Python&Pails
2
(['"])[^\1]*\1
Single or double-quoted string. \1 matches whatever the 1st group matched. \2 matches
whatever the 2nd group matched, etc.
Alternatives
1
python|perl
Matches "python" or "perl"
2
rub(y|le))
Matches "ruby" or "ruble"
3
Python(!+|\?)
103
Perl Tutorial for Beginners
Anchors
This need to specify match positions.
1
^Python
Matches "Python" at the start of a string or internal line
2
Python$
Matches "Python" at the end of a string or line
3
\APython
Matches "Python" at the start of a string
4
Python\Z
Matches "Python" at the end of a string
5
\bPython\b
Matches "Python" at a word boundary
6
\brub\B
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
7
Python(?=!)
Matches "Python", if followed by an exclamation point
8
Python(?!!)
Matches "Python", if not followed by an exclamation point
104
Perl Tutorial for Beginners
1
R(?#comment)
Matches "R". All the rest is a comment
2
R(?i)uby
Case-insensitive while matching "uby"
3
R(?i:uby)
Same as above
4
rub(?:y|le))
Group only without creating \1 backreference
$to = 'abcd@gmail.com';
$from = 'webmaster@yourdomain.com';
$subject = 'Test Email';
$message = 'This is test email sent by Perl Script';
# Email Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
# Email Body
print MAIL $message;
close(MAIL);
print "Email Sent Successfully\n";
Actually, the above script is a client email script, which will draft email and submit to the server
running locally on your Linux/Unix machine. This script will not be responsible for sending email to
105
Perl Tutorial for Beginners
actual destination. So you have to make sure email server is properly configured and running on
your machine to send email to the given email ID.
$to = 'abcd@gmail.com';
$from = 'webmaster@yourdomain.com';
$subject = 'Test Email';
$message = '<h1>This is test email sent by Perl Script</h1>';
# Email Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Content-type: text/html\n";
# Email Body
print MAIL $message;
close(MAIL);
print "Email Sent Successfully\n";
$to = 'abcd@gmail.com';
$cc = 'efgh@mail.com';
$from = 'webmaster@yourdomain.com';
106
Perl Tutorial for Beginners
$msg = MIME::Lite->new(
From => $from,
To => $to,
Cc => $cc,
Subject => $subject,
Data => $message
);
$msg->send;
print "Email Sent Successfully\n";
$to = 'abcd@gmail.com';
$cc = 'efgh@mail.com';
$from = 'webmaster@yourdomain.com';
$subject = 'Test Email';
$message = '<h1>This is test email sent by Perl Script</h1>';
$msg = MIME::Lite->new(
From => $from,
To => $to,
Cc => $cc,
Subject => $subject,
Data => $message
);
Sending an Attachment
If you want to send an attachment, then following script serves the purpose −
#!/usr/bin/perl
use MIME::Lite;
$to = 'abcd@gmail.com';
$cc = 'efgh@mail.com';
$from = 'webmaster@yourdomain.com';
$subject = 'Test Email';
$message = 'This is test email sent by Perl Script';
107
Perl Tutorial for Beginners
$msg = MIME::Lite-=>new(
From => $from,
To => $to,
Cc => $cc,
Subject => $subject,
Type => 'multipart/mixed'
);
Object Basics
There are three main terms, explained from the point of view of how Perl handles objects. The
terms are object, class, and method.
• An object within Perl is merely a reference to a data type that knows what class it belongs to. The object
is stored as a reference in a scalar variable. Because a scalar only contains a reference to the object, the
same scalar can hold different objects in different classes.
• A class within Perl is a package that contains the corresponding methods required to create and
manipulate objects.
108
Perl Tutorial for Beginners
• A method within Perl is a subroutine, defined with the package. The first argument to the method is an
object reference or a package name, depending on whether the method affects the current object or the
class.
Perl provides a bless() function, which is used to return a reference which ultimately becomes an
object.
Defining a Class
It is very simple to define a class in Perl. A class is corresponding to a Perl Package in its simplest
form. To create a class in Perl, we first build a package.
A package is a self-contained unit of user-defined variables and subroutines, which can be re-used
over and over again.
Perl Packages provide a separate namespace within a Perl program which keeps subroutines and
variables independent from conflicting with those in other packages.
To declare a class named Person in Perl we do −
package Person;
The scope of the package definition extends to the end of the file, or until another package keyword
is encountered.
109
Perl Tutorial for Beginners
Defining Methods
Other object-oriented languages have the concept of security of data to prevent a programmer from
changing an object data directly and they provide accessor methods to modify object data. Perl
does not have private variables but we can still use the concept of helper methods to manipulate
object data.
Lets define a helper method to get person’s first name −
sub getFirstName {
return $self->{_firstName};
}
Another helper function to set person’s first name −
sub setFirstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}
Now lets have a look into complete example: Keep Person package and helper functions into
Person.pm file.
#!/usr/bin/perl
package Person;
sub new {
my $class = shift;
my $self = {
_firstName => shift,
_lastName => shift,
_ssn => shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
sub setFirstName {
my ( $self, $firstName ) = @_;
110
Perl Tutorial for Beginners
sub getFirstName {
my( $self ) = @_;
return $self->{_firstName};
}
1;
Now let's make use of Person object in employee.pl file as follows −
#!/usr/bin/perl
use Person;
Inheritance
Object-oriented programming has very good and useful concept called inheritance. Inheritance
simply means that properties and methods of a parent class will be available to the child classes.
So you don't have to write the same code again and again, you can just inherit a parent class.
For example, we can have a class Employee, which inherits from Person. This is referred to as an
"isa" relationship because an employee is a person. Perl has a special variable, @ISA, to help with
this. @ISA governs (method) inheritance.
Following are the important points to be considered while using inheritance −
• Perl searches the class of the specified object for the given method or attribute, i.e., variable.
• Perl searches the classes defined in the object class's @ISA array.
• If no method is found in steps 1 or 2, then Perl uses an AUTOLOAD subroutine, if one is found in the
@ISA tree.
• If a matching method still cannot be found, then Perl searches for the method within the UNIVERSAL
class (package) that comes as part of the standard Perl library.
111
Perl Tutorial for Beginners
• If the method still has not found, then Perl gives up and raises a runtime exception.
So to create a new Employee class that will inherit methods and attributes from our Person class,
we simply code as follows: Keep this code into Employee.pm.
#!/usr/bin/perl
package Employee;
use Person;
use strict;
our @ISA = qw(Person); # inherits from Person
Now Employee Class has all the methods and attributes inherited from Person class and you can
use them as follows: Use main.pl file to test it −
#!/usr/bin/perl
use Employee;
Method Overriding
The child class Employee inherits all the methods from the parent class Person. But if you would
like to override those methods in your child class then you can do it by giving your own
implementation. You can add your additional functions in child class or you can add or modify the
functionality of an existing methods in its parent class. It can be done as follows: modify
Employee.pm file.
#!/usr/bin/perl
package Employee;
use Person;
use strict;
our @ISA = qw(Person); # inherits from Person
# Override constructor
112
Perl Tutorial for Beginners
sub new {
my ($class) = @_;
sub getLastName {
my( $self ) = @_;
return $self->{_lastName};
}
1;
Now let's again try to use Employee object in our main.pl file and execute it.
#!/usr/bin/perl
use Employee;
Default Autoloading
Perl offers a feature which you would not find in any other programming languages: a default
subroutine. Which means, if you define a function called AUTOLOAD(), then any calls to undefined
subroutines will call AUTOLOAD() function automatically. The name of the missing subroutine is
accessible within this subroutine as $AUTOLOAD.
Default autoloading functionality is very useful for error handling. Here is an example to implement
AUTOLOAD, you can implement this function in your own way.
sub AUTOLOAD {
my $self = shift;
my $type = ref ($self) || croak "$self is not an object";
my $field = $AUTOLOAD;
$field =~ s/.*://;
unless (exists $self->{$field}) {
croak "$field does not exist in object/class $type";
}
if (@_) {
return $self->($name) = shift;
} else {
return $self->($name);
}
}
114
Perl Tutorial for Beginners
package MyClass;
...
sub DESTROY {
print "MyClass::DESTROY called\n";
}
#!/usr/bin/perl
sub new {
print "MyClass::new called\n";
my $type = shift; # The package/type name
my $self = {}; # Reference to empty hash
return bless $self, $type;
}
sub DESTROY {
print "MyClass::DESTROY called\n";
}
sub MyMethod {
print "MyClass::MyMethod called!\n";
}
sub new {
print "MySubClass::new called\n";
my $type = shift; # The package/type name
my $self = MyClass->new; # Reference to empty hash
return bless $self, $type;
}
sub DESTROY {
print "MySubClass::DESTROY called\n";
}
sub MyMethod {
my $self = shift;
$self->SUPER::MyMethod();
print " MySubClass::MyMethod called!\n";
115
Perl Tutorial for Beginners
$myObject = MyClass->new();
$myObject->MyMethod();
$myObject2 = MySubClass->new();
$myObject2->MyMethod();
116