100% found this document useful (1 vote)
155 views52 pages

Osp Perl Document

Perl is a general purpose programming language that is stable, cross platform, and open source. It was originally designed for text manipulation but is now used for a wide range of tasks including web development, system administration, and more. Perl supports object oriented, procedural, and functional programming. It has over 25,000 third party modules available to easily extend its capabilities.

Uploaded by

sandhiya p
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
155 views52 pages

Osp Perl Document

Perl is a general purpose programming language that is stable, cross platform, and open source. It was originally designed for text manipulation but is now used for a wide range of tasks including web development, system administration, and more. Perl supports object oriented, procedural, and functional programming. It has over 25,000 third party modules available to easily extend its capabilities.

Uploaded by

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

Unit – 4

Perl back grounder-perl overview-perl parsing rules -


variables &data-statements &control structures-subroutines-
packages &modules – working with files – data manipulation
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 features:
1. Mission critical

Used for mission critical projects in the public and private


sectors.

2. Object-oriented, procedural and functional


Supports object-oriented, procedural and functional
programming.

3. Easily extendible

There are over 25,000 open source modules available from the
Comprehensive Perl Archive Network (CPAN).

4. Text manipulation

Perl includes powerful tools for processing text that make it ideal
for working with HTML, XML, and all other mark-up and natural
languages.

5. Unicode support

Supports Unicode version 6 (from Perl 5.14).

6. Database integration

Perl's database integration interface (DBI) supports third-party


databases including Oracle,
Sybase, Postgres, MySQL and many others.

7. C/C++ library interface

Perl interfaces with external C/C++ libraries through XS or SWIG.

8. Embeddable

The Perl interpreter can be embedded into other systems such


as web servers and database servers.

9. Open Source

Perl is Open Source software, licensed under its Artistic License,


or the GNU General Public License (GPL).
Perl and the Web:
• Ideal web programming language
• Web Frameworks
• Database integration
• Web modules
• Duct-tape of the internet, and more...
• Encryption capable
• Embed into Apache

Advantages of Perl:

• Perl Provides supports for cross platform and it is compatible with


mark-up languages like HTML, XML etc.
• It is very efficient in text-manipulation i.e. Regular Expression. It
also provides the socket capability.
• It is free and a Open Source software which is licensed
under Artistic and GNU General Public License (GPL).
• It is an embeddable language that’s why it can embed in web
servers and database servers.
• It supports more than 25, 000 open source modules
on CPAN(Comprehensive Perl Archive Network) which provide
many powerful extensions to the standard library. For example,
XML processing, GUI(Graphical User Interface) and DI(Database
Integration) etc.

Disadvantages of Perl:

• Perl doesn’t supports portability due to CPAN modules.


• Programs runs slowly and program needs to be interpreted each
time when any changes are made.
• In Perl, the same result can be achieved in several different ways
which make the code untidy as well as unreadable.
• Usability factor is lower when compared to other languages.
Applications:

• One of the major application of Perl language is to processing of


text files and analysis of the strings.
• Perl also used for CGI( Common Gateway Interface) scripts.
• Used in web development, GUI(Graphical User Interface)
development.
• Perl’s text-handling capabilities is also used for generating SQL
queries.

Programming in Perl:
• Since the Perl is a lot similar to other widely used languages
syntactically, it is easier to code and learn in Perl.
• Programs can be written in Perl in any of the widely used text
editors like Notepad++, gedit etc.
• After writing the program save the file with the
extension .pl or .PL
• To run the program use perl file_name.pl on the command line.

Example:

A simple program to print Welcome to GFG!

# Perl program to print Welcome to GFG!


#!/usr/bin/perl
# Below line will print "Welcome to GFG!"
print "Welcome to GFG!\n";
Output:
Welcome to GFG!
Comments:
Comments are used for enhancing the readability of the code. The
interpreter will ignore the comment entries and does not execute
them. There are two types of comment in Perl:
Single line comments:
• Perl single line comment starts with hashtag symbol with no
white spaces (#) and lasts till the end of the line.
• If the comment exceeds one line then put a hashtag on the next
line and continue the comment.
• Perl’s single line comments are proved useful for supplying short
explanations for variables, function declarations, and
expressions.

Syntax:
# Single line comment
Example:
#!/usr/bin/perl
$b = 10; # Assigning value to $b
$c = 30; # Assigning value to $c
$a = $b + $c; # Performing the operation
print "$a"; # Printing the result

Multi-line string as a comment:


• Perl multi-line comment is a piece of text enclosed within “=”
and “=cut”.
• They are useful when the comment text does not fit into one
line; therefore needs to span across lines.
• Multi-line comments or paragraphs serve as documentation for
others reading your code.
• Perl considers anything written after the ‘=’ sign as a comment
until it is accompanied by a ‘=cut’ at the end.
• Please note that there should be no whitespace after the ‘=’
sign.
Syntax:

= Multi line comments


Line start from = is interpreted as the
starting of multiline comment and =cut is
consider as the end of multiline comment
=cut

Example:
#!/usr/bin/perl
=Assigning values to
variable $b and $c
=cut
$b = 10;
$c = 30;
=Performing the operation
and printing the result
=cut
$a = $b + $c;
print "$a";

PERL OVERVIEW
❖ According to Wall, Perl has two slogans.
❖ The first is "There's more than one way to do it," commonly known as TMTOWTD.
❖ The second slogan is "Easy things should be easy and hard things should be possible".
OVERVIEW
❖ Features
❖ Design
❖ Appilication
❖ Implementation
❖ Availability
❖ Database interfaces
❖ Comparative performance
❖ Optimizing

FEATURES
❖ The overall structure of Perl derives broadly from C.
❖ Perl is procedural in nature, with variables ,expressions,assignment statements, brace-
delimited blocks, control structures,
subroutines.
❖ Perl also takes features from shell programming.
❖ All variables are marked with leading sigils, which allow variables
to be interpolated directly into strings.
❖ 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 supports both procedural and object-oriented programming.
❖ Perl interfaces with external C/C++ libraries through XS or SWIG.
❖ Perl is extensible. There are over 20,000 third party modules available from the
Comprehensive Perl Archive Network (CPAN).
❖ The Perl interpreter can be embedded into other systems..

Design
❖ The design of Perl can be understood as a response to
three broad trends in the
computer industry: falling hardware costs, rising labor
costs, and improvements in compiler technology.
❖ Many earlier computer languages, such as Fortran and C,aimed to make efficient use
of expensive computer hardware.
❖ In contrast, Perl was designed so that computer programmers could write programs
more quickly and easily.
❖ Perl does not enforce any particular programming paradigm (procedural, object-
oriented, functional, or others) or even require the programmer to choose among
them.
❖ No written specification or standard for the Perl language exists for Perl versions
through Perl 5, and there are no plans to create one for the current version of Perl.
❖ There has been only one implementation of the interpreter, and the language has
evolved along with it.

❖ Perl has many features that ease the task of the programmer at the expense of
greater CPU and memory requirements.
❖ These include automatic memory management; dynamic typing; strings, lists, and
hashes; regular expressions; introspection; and an eval() function.

Application
❖ Perl has many and variety applications, compounded by the availability of many
standard and third-party modules.
❖ Perl has chiefly been used to write CGI scripts: large projects written in Perl
include cPanel, Slash, Bugzilla, RT, TWiki,
❖ It is also an optional component of the popular LAMP technology stack for Web
development, in lieu of PHP or Python.
❖ Perl is used extensively as a system programming language in the Debian GNU/Linux
distribution.[81]
❖ The combination makes Perl a popular all-purpose language for system administrators,
particularly because short programs, often called "one-liner programs," can be entered
and run on a single command line.
❖ Perl code can be made portable across Windows and Unix; such code is often used by
suppliers of software to simplify packaging and maintenance of software build- and
deployment-scripts
Perl is available on a wide variety of platforms −.

❖ Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc


❖ Win 9x/NT/2000/
❖ WinCE
❖ Macintosh (PPC, 68K)
❖ Solaris (x86, SPARC)
❖ OpenVMS
❖ Alpha (7.2 and later)

❖ Graphical user interfaces (GUIs) may be developed using Perl.

❖ For example, Perl/Tk and wxPerl are commonly used to enable user interaction with
Perl scripts. Such interaction may be synchronous or asynchronous, using callbacks to
update the GUI.

Implementation
❖ Perl is implemented as a core interpreter, written in C,together with a large collection
of modules, written in Perl and C.
❖ The interpreter has an object-oriented architecture. All of the elements
of the Perl language scalars, arrays, hashes, coderefs, file handlesare representent in
the interpreter by C structs.
❖ The life of a Perl interpreter divides broadly into a compile phase and a run phase. [83]
❖ In Perl, the phases are the major stages in the interpreter's life-cycle. Each interpreter
goes through each phase only once, and the phases follow in a fixed sequence.
❖ Perl is distributed with over 250,000 functional tests for core Perl
language.

Availability
❖ Perl is dual licensed under both the Artistic License 1.0 and
the GNU General Public License.[6] Distributions are available for
most operating systems. It is particularly prevalent
on Unix and Unix-like systems, but it has been ported to most
modern (and many obsolete) platforms.
❖ Because of unusual changes required for the classic Mac
OS environment, a special port called MacPerl was shipped
independently.[89
❖ The Comprehensive Perl Archive Network carries a complete
list of supported platforms with links to the distributions
available on each.

Optimizing
❖ Because Perl is an interpreted language, it can give
problems when efficiency is critical; in such situations, the
most critical routines can be written in other languages (such
as C), which can be connected to Perl via simple In line
modules or the more complex but flexible XS mechanism.

Database interfaces
❖ Perl's text-handling capabilities can be used for
generating SQL queries; arrays, hashes, and automatic
memory management make it easy to collect and process the
returned data In Perl 5, database interfaces are implemented
by Perl DBI modules.
❖ The DBI (Database Interface) module presents a single,
database independent interface to Perl applications, while the
DBD (Database Driver) modules handle the details of
accessing some 50 different databases; there are DBD drivers
for most ANSI SQL databases.

Comparative performance
❖ The Computer Language Benchmarks compares the
performance of implementations of typical programming
problems in several programming languages.
❖ Large Perl programs start more slowly than similar programs in
compiled languages because perl has to compile the source
every time it runs.
❖ In a talk at the YAPC::Europe 2005 conference and
subsequent article "A Timely Start," Jean-Louis Leroy found
that his Perl programs took much longer to run than expected
because the perl interpreter spent significant time finding
modules within his over-large include path.
❖ Once Perl code is compiled, there is additional
overhead during the execution phase that typically is
not present for programs written in compiled languages
such as C or C++.[1

PERL DATATYPES AND VARIABLES


Perl Data Types:
● Data types specify the type of data that a valid Perl variable can hold. Perl
is a loosely typed language.
● There is no need to specify a type for the data while using in the Perl
program.
● The Perl interpreter will choose the type based on the context of the data
itself.
There are 3 data types in Perl as follows:
1. Scalars
2. Arrays
3. Hashes(Associative Arrays)

1. Scalars:
● It is a single unit of data which can be an integer number, floating point, a
character, a string, a paragraph, or an entire web page.
● They are preceded by a dollar sign ($).

Example:
# Perl Program to demonstrate the
# Scalars data types
# An integer assignment
$age = 1;
# A string
$name = "ABC";
# A floating point
$salary = 21.5;
# displaying result
print "Age = $age\n";
print "Name = $name\n";
print "Salary = $salary\n";
Output:
Age = 1
Name = ABC
Salary = 21.5
● Scalar Operations:
− There are many operations which can be performed on the scalar
data types like addition, subtraction, multiplication etc.

Example:
# Perl Program to demonstrate
# the Scalars operations
#!/usr/bin/perl
# Concatenates strings
$str = "GFG" . " is the best";
# adds two numbers
$num = 1 + 0;
# multiplies two numbers
$mul = 4 * 9;
# concatenates string and number
$mix = $str . $num;
# displaying result
print "str = $str\n";
print "num = $num\n";
print "mul = $mul\n";
print "mix = $mix\n";
Output:
str = GFG is the best
num = 1
mul = 36
mix = GFG is the best1

2. Arrays:
● An array is a variable that stores the value of the same data type in the
form of a list.
● To declare an array in Perl, we use ‘@’ sign in front of the variable
name.

Example:
@age=(10, 20, 30)
It will create an array of integers which contains the value 10, 20 and 30. To
access a single element of an array, we use the ‘$’ sign.
$age[0]
It will produce the output as 10.
Example:

# Perl Program to demonstrate


# the Arrays data type
#!/usr/bin/perl
# creation of arrays
@ages = (33, 31, 27);
@names = ("Geeks", "for", "Geeks");
# displaying result
print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";

Output:
$ages[0] = 33
$ages[1] = 31
$ages[2] = 27
$names[0] = Geeks
$names[1] = for
$names[2] = Geeks

3. Hashes(Associative Arrays):
● It is a set of key-value pair.
● It is also termed as the Associative Arrays.
● To declare a hash in Perl, we use the ‘%’ sign. To access the particular
value, we use the ‘$’ symbol which is followed by the key in braces.
Example:
#!/usr/bin/perl
%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
print "\$data{'John Paul'} = $data{'John Paul'}\n";
print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

This will produce the following result −


$data{'John Paul'} = 45
$data{'Lisa'} = 30
$data{'Kumar'} = 40

Perl Variables:

● Variables in Perl are used to store and manipulate data throughout the
program.
● When a variable is created it occupies memory space.
● The data type of a variable helps the interpreter to allocate memory and
decide what to be stored in the reserved memory.
● Therefore, variables can store integers, decimals, or strings with the
assignment of different data types to the variables.

Naming of a Variable:
A variable in Perl can be named anything with the use of a specific
datatype. There are some rules to follow while naming a variable:
● Variables in Perl are case sensitive.
Example:
$John and $john are two different variables
● It starts with $, @ or % as per the datatype required, followed by zero or
more letters, underscores and digits
● Variables in Perl cannot contain white spaces or any other special character
except underscore.
Example:
$my-name = "John"; // Invalid
$my name = "John"; // Invalid
$my_name = "John"; // Valid

Declaration of a Variable
Variable Declaration is done on the basis of the datatype used to define the
variable. These variables can be of three different datatypes:
● Scalar Variables: It contains a single string or numeric value. It starts with
$ symbol.
Syntax: $var_name = value;
Example:
$item = "Hello"
$item_one = 2
● Array Variables: It contains a randomly ordered set of values. It starts
with @ symbol.
Syntax : @var_name = (val1, val2, val3, …..);
Example:
@price_list = (70, 30, 40);
@name_list = ("Apple", "Banana", "Guava");
● Hash Variables: It contains (key, value) pair efficiently accessed per key.
It starts with % symbol.
Syntax : @var_name = (val1 = key1, val2 = key2, val3 = key3, …..);
Example:
%item_pairs = ("Apple" =>2, "Banana'=>3);
%pair_random = ("Hi" =>8, "Bye"=>9);

Modification of a Variable

Perl allows to modify its variable values anytime after the variable declaration is
done. There are various ways for the modification of a variable:
● A scalar variable can be modified simply by redefining its value.
Example:
$name = "John";
# This can be modified by simply
# redeclaring the variable $name.
$name = "Rahul";
● An element of an array can be modified by passing the index of that
element to the array and defining a new value to it.
Example:
@array = ("A", "B", "C", "D", "E");
# If value of second variable is to
# be modified then it can be done by
@array[2] = "4";
# This will change the array to,
# @array = ("A", "B", "4", "D", "E");
● A value in a hash can be modified by using its Key.
Example:
%Hash = ("A", 10, "B", 20, "C", 30)
# This will modify the value
# assigned to Key 'B'
$Hash{"B"} = 46;
%Hash = (“A”, 10, ”B”, 46, ”C”, 30)

Variable Interpolation:
● Perl provides various methods to define a String to a variable.
● This can be done with the use of single quotes, double quotes, using q-
operator and double-q operator, etc.
● Using single quotes and double quotes for writing strings is same but
there exists a slight difference between how they work.
● Strings which are written with the use of single quotes display the content
written within it exactly as it is.
Example:
$name = "John"
print 'Hi $name\nHow are you?'
The above code will print:
Hi $name\nHow are you?
Whereas strings written within double quotes replace the variables with their
value and then displays the string. It even replaces the escape sequences by their
real use.
Example:
$name = "John"
print "Hi $name\nHow are you?"
The above code will print:
Hi John
How are you?
Example Code:

#!/usr/bin/perl
use Data::Dumper;
# Scalar Variable
$name = "GeeksForGeeks";
# Array Variable
@array = ("G", "E", "E", "K", "S");
# Hash Variable
%Hash = ('Welcome', 10, 'to', 20, 'Geeks', 40);

# Variable Modification
@array[2] = "F";
print "Modified Array is @array\n";
# Interpolation of a Variable
# Using Single Quote
print 'Name is $name\n';
# Using Double Quotes
print "\nName is $name";
# Printing hash contents
print Dumper(\%Hash);
Output:
Modified Array is G E F K S
Name is $name\n
Name is GeeksForGeeks$VAR1 = {
'to' => 20,
'Welcome' => 10,
'Geeks' => 40
}

STATEMENT AND CONTROL STRUCTURES:-


PERL DEFINTION:

• Perl is a programming language.


• It’s interpreted.
• It’s designed for text processing.
• It’s general-purpose, high-level-language.

A program is a collection of statements. After the program


executes one statement, it "moves" to the next statement and
executes that one. If you imagine that a statement is a
stepping stone, then you can also think of the execution flow
of the program as a sequence of "stones".

Operators:

➢ Although any expression can be used as a condition, is usually


one that is built from relational operators and/or logical
operators.

Relational operators:
• Relational operators are operators that compare two expressions.
• In math we use operators like >, <, and ≠ to compare numeric
expressions.
• There are six numeric relational operators in Perl, which are listed in
the next slide.
Logical operators:
The following are logical operators in Perl:

➢ $a && $b performs logical AND of two variables or expressions. The


logical && operator checks if both variables or expressions are true.
➢ $a || $b performs logical OR of two variables or expressions. The
logical || operator checks either a variable or expression is true.
➢ !$a performs logical NOT of the variable or expression. The
logical ! operator inverts the value of the followed variable or
expression. In the other words, it converts true to false or false to true.

Types of conditional statements:


Sr.No. Statement & Description

1 if statement

An if statement consists of a boolean expression followed by one or more


statements.

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.

1.The if statement:-
➢ If the boolean expression evaluates to true then the block of code inside
the if statement will be executed.
➢ If boolean expression evaluates to false then the first set of code after the
end of the if statement (after the closing curly brace) will be executed.
Flow Diagram:

Syntax:
If(expression)
{ statement1;
Statement2;…
}
Example:
$a = 1;

if($a == 1)

print("Welcome to the Perl if tutorial!\n");}

2.If-else statement:
Perl provides the if else statement that allows you to execute a

code block if the expression evaluates to true , otherwise, the
code block inside the else branch will execute.
Flow chart:
Syntax:
if(expression){

//if code block;

}else{

//else code block;

Example:
$a = 1;

$b = 2;

if($a == $b){
print("a and b are equal\n");

}else{

print("a and b are not equal\n");

3.if...elsif...else statement:

An if statement can be followed by an optional elsif...else statement, which is very


useful to test the various conditions using single if...elsif statement.
When using if , elsif , else statements there are few points to keep in mind.
• An if can have zero or one else's and it must come after any elsif's.
• An if can have zero to many elsif's and they must come before the else.
• Once an elsif succeeds, none of the remaining elsif's or else's will be tested.

Flow chart:

Syntax
if(expression){

...

}elsif(expression2){

...

}elsif(expression3{

...

}else{

...

}
Example:
$a = 1;

$b = 2;

if($a == $b){

print("a and b are equal\n");

}elsif($a > $b){

print("a is greater than b\n");

}else{

print("a is less than b\n");


}

4.unless statement:
Perl executes the statement from right to left, if the condition is

false , Perl executes the statement that precedes the unless .


➢ If the condition is true , Perl skips the statement.

➢ If the condition evaluates to false , Perl executes the code block,

otherwise, it skips the code block.


Flow Chart:

Syntax:
unless(condition){

// code block

}
Example:
$a = 10;

unless($a <= 0){

print("a is greater than 0\n")

5.unless...else statement:
➢ Similar to unless statement, the unless-else statement in Perl behaves
opposite to the if-else statement.
➢ In unless-else, the statements inside unless gets executed if the
condition is false and statements inside else gets executed if the
condition is true.
Flow chart:

Syntax:
unless(condition){

// unless code block

}else{

// else code block

}
Example:
$a = 10;

unless($a >= 0){

print("a is less than 0\n");

}else{

print("a is greater than or equal 0\n");

6.Unless elseif else statement:


➢ If you have more than one condition to check with
the unless statement, you can use the unless elsif else statement
as follows:

Syntax:
unless(condition_1){

// unless code block

}elsif(condition_2){

// elsif code block

}else{

// else code block

Example:
#!/usr/local/bin/perl

$a = 20;

# check the boolean condition using if statement

unless( $a == 30 ) {

# if condition is false then print the following

printf "a has a value which is not 20\n";

} elsif( $a == 30 ) {
# if condition is true then print the following

printf "a has a value which is 30\n";

} else {

# if none of the above conditions is met

printf "a has a value which is $a\n";

7.Switch statement:
➢ A switch statement allows a variable to be tested for equality
against a list of values.
➢ Each value is called a case, and the variable being switched on is
checked for each switch case.

Flow Diagram:

Syntax:
given(expression)
{
when ( first value)
{
statement to be executed;
}
when (second value)
{
statement to be executed;
}
....
...
when (nth value)
{
statement to be executed;
}
default
{
statement to be executed if all the cases are not matched.;
}
}

Example:
use feature qw(switch say);
print "Enter the Number for the Week \n";
chomp( my $week = <> );
given ($week)
{
when('1')
{
say "Monday";
}
when('2')
{
say "Tuesday";
}
when('3')
{
say "Wednesday";
}
when('4')
{
say "Thursday";
}
when('5')
{
say "Friday";
}
when('6')
{
say "Saturday";
}
when('7')
{
say "Sunday";
}
default
{
say "Please Enter valid Week Number";
}
}

Loops
Looping in programming languages is a feature which facilitates the execution of a set
of instructions or functions repeatedly while some condition evaluates to true. Loops make
the programmers task simpler. Perl provides the different types of loop to handle the
condition based situation in the program. The loops in Perl are :
• for loop
• foreach loop
• while loop
• do…. while loop
• until loop
• Nested loops
for Loop
“for” loop provides a concise way of writing the loop structure. A for statement consumes
the initialization, condition and increment/decrement in one line thereby providing a shorter,
easy to debug structure of looping.

Syntax:
for (init statement; condition; increment/decrement )
{
# Code to be Executed
}

Flow Chart:

Example :

# Perl program to illustrate


# the for loop

# for loop
for ($x =10; $x<=15 ; $x++)
{
print "$x\n"
}

Output:
10
11
12
13
14
15
foreach Loop
A foreach loop is used to iterate over a list and the variable holds the value of the
elements of the list one at a time. It is majorly used when we have a set of data in a list and
we want to iterate over the elements of the list instead of iterating over its range. The process
of iteration of each element is done automatically by the loop.
Syntax:
foreach variable
{
# Code to be Executed
}

Flow Chart:

Example:

# Perl program to illustrate


# the foreach loop

# Array
@data = ('GEEKS', 'FOR', 'GEEKS');
# foreach loop
foreach $word (@data)
{
print $word
}
Output:
GEEKSFORGEEKS

while Loop
• A while loop generally takes an expression in parenthesis.
• If the expression is True then the code within the body of while loop is executed.
• It is also known as a entry controlled loop as the condition is checked before
executing the loop.
Syntax :
while (condition)
{
# Code to be executed
}

Flow Chart:

Example :

# Perl program to illustrate


# the while loop

# while loop
$count = 3;
while ($count >= 0)
{
$count = $count - 1;
print "GeeksForGeeks\n";
}
Output:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
Infinite While Loop: While loop can execute infinite times which means there is no
terminating condition for this loop. In other words, we can say there are some conditions
which always remain true, which causes while loop to execute infinite times or we can say it
never terminates.

# Perl program to illustrate


# the infinite while loop

# infinite while loop


# containing condition 1
# which is always true
while(1)
{
print "Infinite While Loop\n";
}
Output:
Infinite While Loop
Infinite While Loop
Infinite While Loop
Infinite While Loop
.
.
.
.

do…. while loop


• A do..while loop is almost same as a while loop.
• The condition is checked after the first execution.
• It is also known as exit controlled loop as the condition is checked after executing
the loop.

Syntax:
do {

# statments to be Executed

} while(condition);
Flow Chart:

Example :

# Perl program to illustrate


# do..while Loop

$a = 10;

# do..While loop
do {

print "$a ";


$a = $a - 1;
} while ($a > 0);
Output:
10 9 8 7 6 5 4 3 2 1

until loop
• until loop is the opposite of while loop. It takes a condition in the parenthesis and it
only runs until the condition is false.
• Basically, it repeats an instruction or set of instruction until the condition is FALSE.
• It is also entry controller loop i.e. first the condition is checked then set of instructions
inside a block is executed.

Syntax:
until (condition)
{
# Statements to be executed
}
Flow Chart:

Example :
# Perl program to illustrate until Loop

$a = 10;

# until loop
until ($a < 1)
{
print "$a ";
$a = $a - 1;
}
Output:
10 9 8 7 6 5 4 3 2 1

Nested Loops
A nested loop is a loop inside a loop. Nested loops are also supported by Perl Programming.
Syntax for while nested loop in Perl:

• Nested while loop


while (condition)
{
while (condition)
{
# Code to be Executed
}
}
Example :
# Perl program to illustrate
# nested while Loop

$a=5;
#outer while loop
while($a>0)
{
$b=1;
#inner while loop
while($b<=$a)
{
print "*";
$b=$b+1;
}
$a=$a-1;
print "\n”;
}
Output:
*****
****
***
**
*
PERL SUBROUTINES

Definition
• A Perl function or subroutine is a group of statements that together perform
a specific task.
• In every programming language user want to reuse the code.
• So the user puts the section of code in function or subroutine so that there
will be no need to write code again and again.
• In Perl, the terms function, subroutine, and method are the same but in
some programming languages, these are considered different.
• The word subroutines is used most in Perl programming because it is
created using keyword sub.
• Whenever there is a call to the function, Perl stop executing all its program
and jumps to the function to execute it and then returns back to the section
of code that it was running earlier.

Define and Call a Subroutine


The general form of a subroutine definition in Perl programming language is as
follows −
sub subroutine_name {
body of the subroutine
}

The typical way of calling that Perl subroutine is as follows −


subroutine_name( list of arguments );

In versions of Perl before 5.0, the syntax for calling subroutines was slightly
different as shown below. This still works in the newest versions of Perl.

&subroutine_name( list of arguments );

Let's have a look into the following example, which defines a simple function
and then call it. Because Perl compiles your program before executing it, it doesn't
matter where you declare your subroutine.
#!/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!

Passing Arguments to a Subroutine


You can pass various arguments to a subroutine like you do in any other
programming language and they can be acessed inside the function using the special
array @_. Thus the first argument to the function is in $_[0], the second is in $_[1],
and so on.
You can pass arrays and hashes as arguments like any scalar but passing
more than one array or hash normally causes them to lose their separate identities.
So we will use references to pass any array or hash.
Let's try the following example, which takes a list of numbers and then prints
their average −

#!/usr/bin/perl

# Function definition
sub rectangle
{
$area=@_[0]*@_[1];
$perimeter=2*(@_[0]+@_[1]);
print "Area of the rectangle is: $area
sq.units\n";
print "Perimeter of the rectangle is: $perimeter
units\n";
}
# Function call
rectangle(10, 20);

Output
Area of the rectangle is: 200 sq.units
Perimeter of the rectangle is: 60 units

Passing Lists to Subroutines


Because the @_ variable is an array, it can be used to supply lists to a
subroutine. However, because of the way in which Perl accepts and parses lists and
arrays, it can be difficult to extract the individual elements from @_. If you have to
pass a list along with other scalar arguments, then make list as the last argument as
shown below −

#!/usr/bin/perl

# Function definition
sub random
{
@hobbies=@_;
print "Hobbies: @hobbies\n";
}
@favs=("Playing Guitar","Playing Chess","Reading
Books");
# Function call with list parameter
random(@favs);
When above program is executed, it produces the following result –
Hobbies: Playing Guitar Playing Chess Reading Books

Passing Hashes to Subroutines


When you supply a hash to a subroutine or operator that accepts a list, then
hash is automatically translated into a list of key/value pairs. For example −

#!/usr/bin/perl
# Function definition
sub PrintHash {
my (%hash) = @_;

foreach my $key ( keys %hash ) {


my $value = $hash{$key};
print "$key : $value\n";
}
}
%hash = ('name' => 'Tom', 'age' => 19);

# Function call with hash parameter


PrintHash(%hash);

When above program is executed, it produces the following result −


name : Tom
age : 19

Returning Value from a Subroutine


You can return a value from subroutine like you do in any other programming
language.
You can return arrays and hashes from the subroutine like any scalar but
returning more than one array or hash normally causes them to lose their separate
identities. So we will use references to return any array or hash from a function.
Let's try the following example, which takes a list of numbers and then returns
their average −

#!/usr/bin/perl

# Function definition
sub circle
{
$radius=@_[0];
return 3.14*$radius*$radius;
}
# Function call
$area=circle(10);
print "The area of the circle is $area sq. units\n";
When above program is executed, it produces the following result −
The area of the circle is 314 sq.units

Private Variables in a Subroutine


By default, all variables in Perl are global variables, which means they can be
accessed from anywhere in the program. But you can create private variables
called lexical variables at any time with the my operator.
The my operator confines a variable to a particular region of code in which it
can be used and accessed. Outside that region, this variable cannot be used or
accessed. This region is called its scope..
Following is an example showing you how to define a single or multiple private
variables using my operator −

#!/usr/bin/perl

# Global variable
$var=500;

# Function definition
sub test {
# Private variable
my $var=50;
print "Value of variable inside the subroutine
$var\n";
}
# Function call
test();
print "Value of variable outside the subroutine
$var\n";

When above program is executed, it produces the following result −

Value of variable inside the subroutine: 50


Value of variable outside the subroutine: 500
Packages and modules
What are Packages?
The package statement switches the current naming context to a
specified namespace (symbol table). Thus −
• A package is a collection of code which lives in its own namespace.
• A namespace is a named collection of unique variable names (also
called a symbol table).
• Namespaces prevent variable name collisions between packages.
• You can explicitly refer to variables within a package using
the :: package qualifier.
Following is an example having main and Foo packages in a file. Here
special variable __PACKAGE__ has been used to print the package
name.
#!/usr/bin/perl

# This is main package


$i = 1;
print "Package name : " , __PACKAGE__ , " $i\n";

package Foo;
# This is Foo package
$i = 10;
print "Package name : " , __PACKAGE__ , " $i\n";

package main;
# This is again main package
$i = 100;
print "Package name : " , __PACKAGE__ , " $i\n";
print "Package name : " , __PACKAGE__ , " $Foo::i\n";

1;

OUTPUT:
Package name : main 1
Package name : Foo 10
Package name : main 100
Package name : main 10

BEGIN and END Blocks


You may define any number of code blocks named BEGIN and END, which act as
constructors and destructors respectively.
BEGIN { ... }
END { ... }
BEGIN { ... }
END { ... }
• Every BEGIN block is executed after the perl script is loaded and compiled but
before any other statement is executed.
• Every END block is executed just before the perl interpreter exits.
• The BEGIN and END blocks are particularly useful when creating Perl
modules.
Following example shows its usage −
#!/usr/bin/perl

package Foo;
print "Begin and Block Demo\n";

BEGIN {
print "This is BEGIN Block\n"
}

END {
print "This is END Block\n"
}

1;

OUTPUT:
This is BEGIN Block
Begin and Block Demo
This is END Block

What are Perl Modules?


• A Perl module is a reusable collection of
related variables and subroutines that perform a set of
programming tasks.
• There are a lot of Perl modules available on the Comprehensive
Perl Archive Network (CPAN).

Perl module example


Suppose you are working on a project that requires logging functionality.
You have done a research on CPAN but didn’t find any module that
meets your requirements. You decided to create your own Perl module.

The first thing comes to your mind is the module name e.g., FileLogger. The
main functionality of the FileLogger module is to:

• Open the log file.


• Write log messages to the log file based on log level.
• Close the log file.

To create FileLogger module, you need to do the following steps:

1. First, create your own module name, in this case, you call it FileLogger.
2. Second, create a file named modulename.pm. In this case, you need to
create a new file named FileLogger.pm. pm stands for Perl module.
3. Third, make the FileLogger module a package by using the

syntax: package FileLogger; at the top of the FileLogger.pm file.

4. Fourth, write the code for subroutines and variables, and put the code
into the FileLogger.pm file.
5. Fifth, put the last statement in the FileLogger.pm file: 1; to make the file
returns true.

Let’s get started to develop the FileLogger module.


1. First, create a new file named FileLogger.pm
2. Second, put the package name at the top of the FileLogger.pm
package FileLogger;
3. Third, put the global variable $LEVEL so that any subroutine can
access it.
my $LEVEL = 1;
4. Fourth, develop subroutines to handle logging functionality. We
need a subroutine to open the log file for writing log messages.

sub open{
my $logfile = shift;
# open log file for appending
open(LFH, '>>', $logfile) or die "cannot open the log file $logfile: $!";
# write time:
print LFH "Time: ", scalar(localtime), "\n";
}
We need another subroutine to append log messages to the log file. We only log
messages if the input log level is lower than the current module’s log level. We
use print() function to write log messages into the log file.
sub log{
my($log_level,$log_msg) = @_;

if($log_level <= $LEVEL){


print LFH "$log_msg\n";
}
}
We need a subroutine to close the log filehandle:
sub close{
close LFH;
}
We could allow other programs to change the log level $LEVEL from the outside
of the module. We can do this by creating a new subroutine set_level(). Inside the
subroutine, we’ll check if the passed log level is a number using a regular
expression before setting the module log level.
sub set_level{
my $log_level = shift;

if($log_level =~ /^\d+$/){
$LEVEL = $log_level;
}
}
Fifth, at the end of the FileLogger.pm file, we put the statement: 1;
Example:
➢ A Perl module file called Foo.pm might contain statements like this.
#!/usr/bin/perl

package Foo;
sub bar {
print "Hello $_[0]\n"
}

sub blat {
print "World $_[0]\n"
}
1;

Few important points about Perl modules:


• The functions require and use will load a module.
• Both use the list of search paths in @INC to find the module.
• Both functions require and use call the eval function to process the
code.
• The 1; at the bottom causes eval to evaluate to TRUE (and thus not
fail).

The Require Function:


A module can be loaded by calling the require function as follows −

#!/usr/bin/perl

require Foo;

Foo::bar( "a" );
Foo::blat( "b" );

You must have noticed that the subroutine names must be fully qualified to call
them. It would be nice to enable the subroutine bar and blat to be imported into
our own namespace so we wouldn't have to use the Foo:: qualifier.

The Use Function:


A module can be loaded by calling the use function.

#!/usr/bin/perl

use Foo;

bar( "a" );
blat( "b" );

Notice that we didn't have to fully qualify the package's function names.
The use function will export a list of symbols from a module given a few added
statements inside a module.

require Exporter;
@ISA = qw(Exporter);

Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by filling the
list variable named @EXPORT: For Example −

package Module;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(bar blat);

sub bar { print "Hello $_[0]\n" }


sub blat { print "World $_[0]\n" }
sub splat { print "Not $_[0]\n" } # Not exported!
1;

Modules in different directory


If a module is present in some sub-directory, then also we use :: to tell the path of
the module. For example, if a module 'b' is present in a sub-directory 'a', then we
use use a::b; to load the module b. Let's see an example to understand this:
#p.pm is defined in directory ab which

#is in parent directory

use strict;

use warnings;

#using package p

use ab::p;

#Function Hello of p

p::Hello();

Working with files:


To read or write files in perl you need to open a file handle. files
handles in perl are yet another kind of variable. they are act as convenient
reference handle, if you will between your program and the operating system
about a particular file.
Perl is an outstanding language for reading from and writing to
files on disk or else where. Begin to incorporate files into your perl programs by
learning how to open, read, write and test files.
To learn:-
• To open and close files
• To write data to files
• To read data from files
• To write perl defensively

Opening files:-
To read or write files in perl you need to open a file handle. File
handles in perl are yet another kind of variable. They act as conversion
reference(handles, if you will) between your program and the operating system
about a particular file. They contain information about how the files was opened
and how far along you are in reading (or writing) the file they also contain user-
definable attributes about how the file is to be read or write
Any time you need to access a file on your disk. You need to create
a new file handled and prepare it by operating the file handled. You open file
handled. Not surprisingly, with the open function. They syntax of open function
is as follows:

open (file handled, path name)


The open function takes a file handles as its first argument and a path name as
the second argument. The path name indicates which file you want to open.so if
you don’t specify a path name such as c:\windows\system\.open will try to open
the file in the current directory.
Closing Files:-
To close a file handled, and therefore disassociate the file handled
from the corresponding file you use the close function. This flushes the
file handle’s buffers and closes the system’s file descriptor.

CLOSE FILE HANDLE


CLOSE
If no FILEHANDLED is specified, then it closes the currently selected file
handled.it returns true only if it could success fully flush the buffers and close
the file.
Path:-
Until now, you’ve opened only files with simple name like novel.txt that
did not include a path. When you try to open a file name that doesn’t specify a
directory name. perl assumes the file is in the current directory. To open a file
that’s in another directory. You must use a path name. the path name describes
the path that perl must take to find the file on your system.

Reading:-
You can read from perl’s file handling in a couple of different ways. The
most common method is to use the file input operator also called the angle
operator(<>). To read a file handle, simply put the file handle name inside the
angle operator and assign the value to a variable.

Open(my file ,”my file”)||die “can’t open my file:


$line=<MYFILE>;
#Reading the file handle
The angle operator in a scalar context reads one line of input from the file.
When called after the entire file has been read, the angle operator returns the
value undef.

Writing:-
To write data to a file, you must first have a file-handle open for writing.
Up till now, all open statements you have seen have opened the file handle for
reading only. The syntax for opening a file for writing is almost identical to that
for reading.

Open(file handle,”>path name”)


Open(file handle,”>>path name”)
The signifies to perl that the file specified at the path name should be over
written with new data, that any existing data should be discarded and the file
handle is open for writing.

Perl Denfensive programming:-


• Use strict
• #!/usr/bin/perl-w
• Check all syscall returns values, printing $:
• Watch for external program failures in$?
• Check$ @ after eval” “or sillee
• Parameter asserts
• #!/usr/bin/perl-T
• Always have an else after a chain of elseif
• Put commands at the end of lists to so your program won’t break
if some one insterts another item at the end of the list.

Data manipulation in perl:


• The simplest uses of perl involve reading or more text files a lines at a
time,changeing The line in fashion, and sending the result to an output file.
• Usually the perl program is stored in a file but simple, “one liner” applications can
be written the commands line after a-e flag as in sed and awk.
• By andy lester, andy manages programmers for follett library resources

❖ -e-command
❖ the diamond operator
❖ n and p ; automatic looping power houses
❖ l: line -ending handling
❖ -i: edit in place
❖ -o[octal]:specify input-record separator

-e command:
• The most useful way to use the command-line options is writing perl one-liners right
in the shell.
• e e-option is the basis for most command-line programs.
• It accepts the value of the parameter as the source text for a program.
• Since this is a single statement in a block, you can omit the semicolon.
• When e-option is uses, perl no longer looks for a program name on the command
line.
$perl-e print “hello,world ! \n “

Escaping shell characters:


• When you re creating command-line programs it’s important to pay attention.
• L’ve quote with single quotes not double quotes for two reasons.
• First, I want to be able to use double quotes doen’t nest in the shell.
• Second, I have to prevent shell interpolation,and single quote make it easy.
• You can escape the shell variables with a backslash.

The diamond operator:


• Perl’s diamond operator, <>,has a great deal of magic built into it making operations
on multiple files easy.so that your program can operator on three files at once?use the
diamond operator instead.
• Perl keeps track on which file your on and opens and clases file handle as appropriate
with the diamond operator.
• Perl keeps the name of currently open file in $ARGV. The $line counter does not reset
at the beginning of each file.The diamond operator figures programming in much perl
command-line magic so , it you to get comfortable with it.

-n and -p: Automatic looping power houses


• The -n and -p options are the real work horse options. They derive from the AWK
metaphor of "Do something to every line in the file" and work closely with the
diamond operator.

-l: Line Ending Handling


• when you're working with lines in a file. You will find you are doing lots chomping
and print in the simplest sense adding -l when you are using -n or -p automatically
does a champ on the input record and adds "\n" after everything you print. It makes
command-line one-line much easier.
• This example only shows the first 40 characters of each line in the input of whether
or not the line is longer than 40 characters not counting the line ending.
• For command-line programmers -l is a good send because it means you can use
print $800 instead of print $800 "\n" to get the result what you want.

-i: Edit in Place


• All the options you've learned so far are great for writing filters where a number of
files or standard input get used out to standard output unfortunately.
• perl comes to the resource again with the -i option. Adding -i tells perl to edit your
files in place.
-o[octal]: specify input record seperate
• When working on the command line you want to specify your input record
seperator.
• This is possible with e BEGIN {$ / : ...}, its easier with the -o option.
• Two special values for the -o option and are -oo for paragraph mode equivalent to
$/="" and -o>>> to entire files equivalent to $/=undef.

You might also like