UNIT 5 - PERL
Pert backgrounder – Pert Overview – Pearl Parsing rules – Variables and data –
Statements and Control structures – Subroutines –Packages and modules- Working with files-
data manipulation
5.1 Pert backgrounder
In 1958, the U.S. Navy introduced network scheduling techniques by developing PERT
as a management control system for the development of the Polaris missile program. PERT’s
focus was to give managers the means to plan and control processes and activities so the project
could be completed within the specified time period. The Polaris program involved 250 prime
contractors, more than 9,000 subcontractors, and hundreds of thousands of tasks.
PERT was introduced as an event-oriented, probabilistic technique to increase the Program
Manager’s control in projects where time was the critical factor and time estimates were difficult
to make with confidence. The events used in this technique represent the start and finish of the
activities. PERT uses three-time estimates for each activity: optimistic, pessimistic, and most
likely. An expected time is calculated based on a beta probability distribution for each activity
from these estimates.
PERT Analysis
Program Evaluation and Review Technique (PERT) is a method used to examine the tasks in a
schedule and determine a Critical Path Method variation (CPM). It analyzes the time required to
complete each task and its associated dependencies to determine the minimum time to complete
a project. It estimates the shortest possible time each activity will take, the most likely length of
time, and the longest time that might be taken if the activity takes longer than expected. The US
Navy developed the method in 1957 on the Polaris nuclear submarine project.
Purpose of PERT Analysis
PERT Analysis informs Program Managers and project personnel on the project’s tasks and the
estimated amount of time required to complete each task. By utilizing this information a Program
Manager will be able to estimate the minimum amount of time required to complete the entire
project. This helps in the creation of more realistic schedules and cost estimates.
Advantages and Disadvantages of PERT Analysis
Understanding the advantages and disadvantages of utilizing PERT analysis will give program
managers and project personnel a better understanding of the realities of their schedules. It takes
an experienced program manager to truly utilize the benefits a PERT analysis can provide a
project team.
Advantages: Provides Program Managers information to evaluate time and resources on
a project. It helps give them the necessary information to make informed decisions and
set a realistic schedule.
Disadvantages: The analysis can be highly subjective and be influenced a few outspoken
team members. It also required a lot of time to continually update the analysis as a
program progresses.
5.2 PERT OVERVIEW
PERT is a method of analyzing the tasks involved in completing a given project,
especially the time needed to complete each task, and to identify the minimum time needed to
complete the total project. It incorporates uncertainty by making it possible to schedule a project
while not knowing precisely the details and durations of all the activities. It is more of an event-
oriented technique rather than start- and completion-oriented, and is used more in those projects
where time is the major factor rather than cost. It is applied on very large-scale, one-time,
complex, non-routine infrastructure and on Research and Development projects.
PERT offers a management tool, which relies "on arrow and node diagrams
of activities and events: arrows represent the activities or work necessary to reach the events or
nodes that indicate each completed phase of the total project."
PERT and CPM are complementary tools, because "CPM employs one time estimation
and one cost estimation for each activity; PERT may utilize three time estimates (optimistic,
expected, and pessimistic) and no costs for each activity. Although these are distinct differences,
the term PERT is applied increasingly to all critical path scheduling
PERT SUMMARY REPORT
Initially PERT stood for Program Evaluation Research Task, but by 1959 was renamed.
[2] It had been made public in 1958 in two publications of the U.S. Department of the Navy,
entitled Program Evaluation Research Task, Summary Report, Phase 1.[4] and Phase 2.[5] In a
1959 article in The American Statistician the main Willard Fazar, Head of the Program
Evaluation Branch, Special Projects Office, U.S. Navy, gave a detailed description of the main
concepts of the PERT. He explained:
Through an electronic computer, the PERT technique processes data representing the
major, finite accomplishments (events) essential to achieve end-objectives; the inter-dependence
of those events; and estimates of time and range of time necessary to complete each activity
between two successive events. Such time expectations include estimates of "most likely time",
"optimistic time", and "pessimistic time" for each activity. The technique is a management
control tool that sizes up the outlook for meeting objectives on time; highlights danger signals
requiring management decisions; reveals and defines both methodicalness and slack in the flow
plan or the network of sequential activities that must be performed to meet objectives; compares
current expectations with scheduled completion dates and computes the probability for meeting
scheduled dates; and simulates the effects of options for decision — before decision.
The concept of PERT was developed by an operations research team staffed with representatives
from the Operations Research Department of Booz Allen Hamilton; the Evaluation Office of
the Lockheed Missile Systems Division; and the Program Evaluation Branch, Special Projects
Office, of the Department of the Navy
Ten years after the introduction of PERT in 1958 the American librarian Maribeth
Brennan published a selected bibliography with about 150 publications on PERT and CPM,
which had been published between 1958 and 1968. The origin and development was summarized
as follows:
PERT originated in 1958 with the ... Polaris missile design and construction scheduling.
Since that time, it has been used extensively not only by the aerospace industry but also in many
situations where management desires to achieve an objective or complete a task within a
scheduled time and cost expenditure; it came into popularity when the algorithm for calculating a
maximum value path was conceived. PERT and CPM may be calculated manually or with a
computer, but usually they require major computer support for detailed projects. A number of
colleges and universities now offer instructional courses in both
For the subdivision of work units in PERT another tool was developed: the Work
Breakdown Structure. The Work Breakdown Structure provides "a framework for complete
networking, the Work Breakdown Structure was formally introduced as the first item of analysis
in carrying out basic PERT/COST
5.3 PERL Parsing Rules
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? (Practical Extraction and Report Language)
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 [Link] 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.
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.
Perl and the Web
Perl used to be the most popular web programming language due to its text manipulation
capabilities and rapid development cycle.
Perl is widely known as "the duct-tape of the Internet".
Perl can handle encrypted Web data, including e-commerce transactions.
Perl can be embedded into web servers to speed up processing by as much as 2000%.
Perl's mod_perl allows the Apache web server to embed a Perl interpreter.
Perl's DBI package makes web-database integration easy.
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 strictly interpreted 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.
5.4 PERL | VARIABLES AND DATA TYPES
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:
There are 3 Types of variables:
1. Scalar Variables: It contains a single string or numeric value. It starts with $
symbol.
Syntax: $var_name = value;
Example:
$item = "Hello"
$item_one = 2
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");
3. Hash Variables: It contains (key, value) pair efficiently accessed per key. It starts
with % symbol.
Syntax : %var_name = ( key1=>val1, key2=>val2, key3=>val3, …..);
Example:
%item_pairs = ("Apple" =>2, "Banana'=>3);
%pair_random = ("Hi" =>8, "Bye"=>9);
Modification of a Variable
Perl allows modifying 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";
# $array[2] = "4"; is an alternate way of updating value in an array.
# 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;
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 the same but there exists a slight
difference between how they work. Strings that 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
display the string. It even replaces the escape sequences with their real use.
Example:
$name = "John"
print "Hi $name\nHow are you?"
The above code will print:
Hi John
How are you?
Example Code:
Perl
#!/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
};
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. To know more about scalars
please refer to Scalars in Perl.
Example:
Perl
# 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 that can be performed on the scalar
data
types like addition, subtraction, multiplication, etc.
Example:
Perl
# 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.
@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 an output as 10. To know more about arrays please refer to Arrays in Perl
Example:
Perl
# 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:
Perl
# Perl Program to demonstrate the
# Hashes data type
# Hashes
%data = ('GFG', 7, 'for', 4, 'Geeks', 11);
#displaying result
print "\$data{'CR'} = $data{'CR'}\n";
print "\$data{'Ramos'} = $data{'Ramos'}\n";
print "\$data{'Bale'} = $data{'Bale'}\n";
Output:
$data{'GFG'} = 7
$data{'for'} = 4
$data{'Geeks'} = 11
[Link]
5.5 STATEMENTS AND CONTROL STRUCTURES
Perl if-else Statement
1. If
2. If-else
3. If else-if
Perl Switch Statement
Perl goto Statement
Perl last Statement
Perl last Statement with LABEL
Perl next Statement
Perl next statement with label
Perl redo Statement
Perl for Loop
Perl Nested for Loop
Perl Infinite for Loop
Perl while Loop
Perl do while Loop
Perl if-else Statement
The if statement in Perl language is used to perform operation on the basis of condition. By using
if-else statement, you can perform operation either condition is true or false. Perl supports
various types of if statements:
o If
o If-else
o If else-if
Perl If Example
The Perl single if statement is used to execute the code if condition is true. The syntax of if
statement is given below:
1. if(expression){
2. //code to be executed
3. }
Flowchart of if statement in Perl
Let's see a simple example of Perl language if statement.
1. $a = 10;
2. if( $a %2==0 ){
3. printf "Even Number\n";
4. }
5. }
Output:
Even Number
Here, output is even number as we have given input as 10.
Perl If-else Example
The Perl if-else statement is used to execute a code if condition is true or false. The syntax of if-
else statement is given below:
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
Flowchart of if-else statement in Perl
Let's see the simple example of even and odd number using if-else statement in Perl language.
1. $a = 10;
2. if( $a %2==0 ){
3. printf "Even Number\n";
4. }else{
5. printf "Odd Number\n";
6. }
Output:
Even Number
Here, input is an even number and hence output is even.
Perl If-else Example with Input from user
In this example, we'll take input from user by using standard input (<STDIN>/<>).
1. print "Enter a Number?\n";
2. $num = <>;
3. if( $num %2==0 ){
4. printf "Even Number\n";
5. }else{
6. printf "Odd Number\n";
7. }
Output:
Enter a Number?
5
Odd Number
Enter a Number?
4
Even Number
In the first output, user has entered number 5 which is odd. Hence the output is odd.
In the second output, user has entered number 4 which is even. Hence the output is even.
Perl If else-if Example
The Perl if else-if statement executes one code from multiple conditions. The syntax of if else-if
statement is given below:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Flowchart of if else-if statement in Perl
The example of if else-if statement in Perl language is given below.
1. print "Enter a Number to check grade\n";
2. $num = <>;
3. if( $num < 0 || $num > 100){
4. printf "Wrong Number\n";
5. }elsif($num >= 0 && $num < 50){
6. printf "Fail\n";
7. }elsif($num >= 0 && $num < 60){
8. printf "D Grade\n";
9. }elsif($num >= 60 && $num < 70){
10. printf "C Grade\n";
11. }elsif($num >= 70 && $num < 80){
12. printf "B Grade\n";
13. }elsif($num >= 80 && $num < 90){
14. printf "A Grade\n";
15. }elsif($num >= 90 && $num <= 100){
16. printf "A+ Grade\n";
17. }
Output:
Enter a Number to check grade
66
C Grade
Enter a Number to check grade
2
Wrong Number
Perl Switch Statement
The perl switch statement is used to execute the code from multiple conditions. There is no case
or switch statement in perl. Instead we use 'when' in place of case and 'given' in place of case.
The syntax of switch statement in perl language is given below:
1. given(expression){
2. when (value1)
3. {//code to be executed;}
4. when (value2)
5. {//code to be executed;}
6. when (value3)
7. {//code to be executed;}
8. default
9. {//code to be executed if all the cases are not matched.}
10. }
Perl Switch Example
Let's see a simple example of c language switch statement.
1. use feature qw(switch say);
2. print "Enter a Number\n ";
3. chomp( my $grade = <> );
4. given ($grade) {
5. when ('10') { say 'It is 10' ;}
6. when ('20') { say 'It is 20' ;}
7. when ('30') { say 'It is 30' ;}
8. default { say 'Not 10, 20 or 30';}
9. }
Output:
Enter a Number
10
It is 10
Enter a Number
55
'Not 10, 20 or 30'
Perl goto Statement
The Perl goto statement is the jump statement. It is used to transfer control by jumping to other
label inside a loop.
There are three goto forms:
goto LABEL:
It jumps to the statement labeled with LABEL and resumes normal execution from there.
goto EXPR:
It is a generalization of goto LABEL. The expression returns a label name and then jumps to that
:For currently running subroutine it substitutes a call to the named subroutine.
Syntax of Perl goto statement is as follows:
1. goto LABEL
2.
3. or
4.
5. goto EXPR
6.
7. or
8.
9. goto &NAME
Perl goto Statement Example
Let's see a simple example to use goto statement in Perl language.
1. LOOP:do
2. print "You are not eligible to vote!\n";
3. print "Enter your age\n";
4. $age = <>;
5. if( $age < 18){
6. goto LOOP;
7. }
8. else{
9. print "You are eligible to vote\n";
10. }
Output:
You are not eligible to vote!
Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!
Perl last Statement
The last statement in Perl is like break statement in C. It is used inside a loop to exit the loop
immediately. In other words, last condition iterates the loop.
The Perl syntax for last statement is given below:
1. last;
Perl last Statement Example
Following is a simple example showing Perl last statement.
1. use warnings;
2. use strict;
3. my ($key, $value);
4. my %rate = ("shoes" => 550,
5. "boots" => 1200,
6. "jaggi" => 800,
7. "jacket" => 1500);
8. print("Please enter an item to know the price:\n");
9. $key = <STDIN>;
10. chomp($key);
11. $value = 0;
12. # searching
13. foreach(keys %rate){
14. if($_ eq $key){
15. $value = $rate{$_};
16. last; }
17. }
18. # result
19. if($value > 0){
20. print("$key costs is Rs. $value \n");
21. }else{
22. print("$key is not in our list. We apologise!!\n");
23. }
Output:
Please enter an item to know the price:
boots
boots costs is Rs. 1200
Please enter an item to know the price:
top
top is not in our list. We apologise!!
In the above program
o When user provides a key, hash elements runs via loop and each hash key is compared
with the key provided by the user.
o If match is found, we exit the loop using last statement otherwise search continues.
o On finding a match result is displayed.
Perl last Statement with LABEL
Using the Perl last statement alone, you can exits only innermost loop. If you want to exit a
nested loop, put a label in the outer loop and pass label to the last statement.
If LABEL is specified with last statement, execution drops out of the loop encountering LABEL
instead of currently enclosing loop.
The Perl syntax for last statement with LABEL is given below:
1. last LABEL;
Perl last Statement with LABEL Example
1. use warnings;
2. use strict;
3. my ($key, $value);
4. my %rate = ("shoes" => 550,
5. "boots" => 1200,
6. "jaggi" => 800,
7. "jacket" => 1500);
8. $value = 0;
9. print("Please enter an item to know the price:\n");
10. OUTER: while(<STDIN>){
11. $key = $_;
12. chomp($key);
13. # searching
14. INNER: foreach(keys %rate){
15. if($_ eq $key){
16. $value = $rate{$_};
17. last outer;
18. }
19. }
20. print("$key is not in our list. We apologise!!\n") if($value ==0);
21. # result
22. }
23. print("$key costs is Rs. $value \n");
Output:
Please enter an item to know the price:
jaggi
boots costs is Rs. 800
Please enter an item to know the price:
jeans
jeans is not in our list. We apologise!!
The above program works in the same way except that it asks the user to enter a search key again
if it couldn't find a match.
Two labels OUTER and INNER are used.
Inside foreach loop, if match is found, we'll exit both the loops because OUTER label is passed
to the last statement.
Perl next Statement
The Perl next statement is like continue statement in C. It helps you to move on to the next
element of your array or hash skipping all the elements in between.
The syntax of Perl next statement is given below:
1. next;
Perl next statement Example
1. @array = (a..z);
2. print("@array\n");
3. for ($index = 0; $index < @array; $index++) {
4. if ($index == 0 || $index == 4 || $index == 8 || $index == 14 || $index == 20) {
5. next;
6. }
7. $array[$index] = "-";
8. }
9. print("@array\n");
Output:
abcdefghijklmnopqrstuvwxyz
a---e---i-----o-----u-----
In the above program, we declared an array, from (a-z).
The alphabetical array is printed as it is.
for loop is used, with next statement for all the vowels.
We have assigned (-) sign to the rest of the array elements other than vowels.
Now due to next statement, only vowel elements will be printed and other elements will be
replaced with (-) sign.
Perl next statement with label
The next label allows you to transfer control to an enclosing loop other than the neighboring
loop.
If label is specified with next statement, execution skips to the next iteration identified with
label.
The syntax of Perl next statement is given below:
1. next LABEL;
Perl next statement with label Example
1. OUTER: for ($i = 0; $i < 3; $i++) {
2. for ($j = 0; $j < 3; $j++) {
3. print("inner: $i,$j\n");
4. if ($j == 1) {
5. next OUTER;
6. }
7. }
8. print("outer: $i,$j\n\n");
9. }
Output:
Inner: 0,0
Inner: 0,1
Inner: 1,0
Inner: 1,1
Inner: 2,0
Inner: 2,1
In the above program, next label jumps to the outer loop and executes for loop just like the next
operator.
Perl redo Statement
The Perl redo statement restarts the current loop without evaluation of the control statement.
Further statements in the block will not be executed.
The syntax of redo statement is given below:
1. redo;
Perl redo statement Example
1. $a = 5;
2. while($a < 150){
3. if( $a == 40 ){
4. $a = $a + 10;
5. redo;
6. }
7. print "a = $a\n";
8. }continue{
9. $a = $a * 2;
10. }
Output:
a=5
a = 10
a = 20
a = 50
a = 100
In the above program, loop restarts at redo condition that is when $a reaches 40.
Perl for Loop
Perl for loop is also known as C-style for loop. The for loop iterates the statement or a part
of the program several times.
It has three parameters:
o Initialize : This part is executed first, and only once. It initializes and declares loop
variable.
o Condition : The for loop executes till the condition is true. When condition is false, loop
execution stops and execution terminates out of the loop.
o Increment/Decrement : The for loop variable increment or decrement as long as it
satisfies the loop condition. When condition is not satisfied loop terminates and output is
printed.
The syntax of for loop in Perl language is given below:
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Flowchart of for loop in Perl
Perl for loop Example:
Let's see the simple program of for loop that prints table of 1.
1. for( $a = 1; $a <= 10; $a++ ){
2. print " $a\n";
3. }
Output:
1
2
3
4
5
6
7
8
9
10
Perl Nested for Loop
In this example, one for loop is nested inside another for loop. Inner loop is executed completely
while outer loop is executed only once. It means if loop is running for 3 times, outer loop will
execute 3 times but inner loop will execute 9 times.
Example:
1. for( $i = 1; $i <= 3; $i++ ){
2. for( $j = 1; $j <= 3; $j++ ){
3. print " $i $j\n";
4. }
5. }
Output:
11
12
13
21
22
23
31
32
33
Perl Infinite for Loop
If double semicolon (;;) is used in for loop, the loop will execute for infinite times. You can stop
the execution using ctrl + c.
1. for( ; ; )
2. {
3. printf "Infinite For Loop\n";
4. }
Output:
Infinite For Loop
Infinite For Loop
Infinite For Loop
Infinite For Loop
Infinite For Loop
Ctrl+c
Perl while Loop
The Perl while loop is used to iterate the part of program or statements many times.
In while loop, condition is given before the statement. When loop execution starts, it first checks
whether the condition is true or false. If condition is true,loop executes. If condition is false, the
loop terminates out of the loop.
Syntax of while loop in C language
The syntax of while loop in Perl language is given below:
1. while(condition){
2. //code to be executed
3. }
Flowchart of while loop in Perl
Perl while loop Example
1. $i = 1;
2. # while loop execution
3. while( $i <= 10 ){
4. printf "$i\n";
5. $i++;
6. }
Output:
1
2
3
4
5
6
7
8
9
10
Perl Nested while Loop Example
In nested while loop, one while loop is used inside another while loop. The inner while loop is
executed completely while outer loop is executed once.
1. $i = 1;
2. # while loop execution
3. while( $i <= 3 ){
4. $j = 1;
5. while( $j <= 3 ){
6. printf "$i $j\n";
7. $j++;
8. }
9. $i++;
10. }
Output:
11
12
13
21
22
23
31
32
33
Perl Infinite while Loop Example
To create infinite while loop, pass true as the test condition. Press ctrl + c to stop the loop
execution.
1. while(true)
2. {
3. printf"Infinitive While Loop\n";
4. }
Output:
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c
Perl do while Loop
Unlike for and while loop, the do while loop checks its condition at the bottom of the loop. So do
while loop will execute at least once.
do while loop syntax
The syntax of Perl language do-while loop is given below:
1. do{
2. //code to be executed
3. }while(condition);
Flowchart of do while loop
Perl do while Example
This is the simple program of Perl do while loop where we are printing the table of 1.
1. $i = 1;
2. # do...while loop execution
do{
3. printf "$i\n";
4. $i++;
5. }while( $i <= 10 );
Output:
1
2
3
4
5
6
7
8
9
10
Perl Nested do while Loop Example
A nested do while loop is the one in which a do while loop is nested inside another do while
loop.
It is executed completely for both inner and outer loops.
Example:
1. $i = 1;
2. # do...while loop execution
3. do{
4. $j = 1;
5. do{
6. printf "$i $j\n";
7. $j++;
8. }while( $j <= 3 );
9. $i++;
10. }while( $i <= 3 );
Output:
11
12
13
21
22
23
31
32
33
Perl Infinite do while Loop Example
By passing true in while condition, infinite do while loop is executed. Its execution can be
stopped by using ctrl + c.
1. do{
2. printf "Infinitive do-while Loop\n";
3. }while( true );
Output:
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c
5.6 Perl | Subroutines or Functions
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 are 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. One can avoid using the return statement.
Defining Subroutines: The general form of defining the subroutine in Perl is as follows-
sub subroutine_name
{
# body of method or subroutine
}
Calling Subroutines: In Perl subroutines can be called by passing the arguments list to it as
follows-
subroutine_name(aruguments_list);
The above way of calling the subroutine will only work with Perl version 5.0 and beyond. Before
Perl 5.0 there was another way of calling the subroutine but it is not recommended to use
because it bypasses the subroutine prototypes.
&subroutine_name(aruguments_list);
Example:
# Perl Program to demonstrate the
# subroutine declaration and calling
#!/usr/bin/perl
# defining subroutine
sub ask_user {
print "Hello Geeks!\n";
# calling subroutine
# you can also use
# &ask_user();
ask_user();
Output:
Hello Geeks!
Passing parameters to subroutines: This is used to pass the values as [Link] is done
using special list array variables ‘$_’. This will assigned to the functions as $_[0], $_[1] and so
on.
Example:
# Perl Program to demonstrate the
# Passing parameters to subroutines
#!/usr/bin/perl
# defining subroutine
sub area
{
# passing argument
$side = $_[0];
return ($side * $side);
}
# calling function
$totalArea = area(4);
# displaying result
printf $totalArea;
Output:
16
Advantage of using subroutines:
It helps us to reuse the code and makes the process of finding error and debug easy.
It helps in organizing the code in structural [Link] of code is organized in sectional
format.
It increases the code readability.
5.7 PERL PACKAGES AND MODULES
Perl has a class-based Object-Oriented (OO) structure that gives us the flexibility to use various
new features, such as packages and modules, in Perl.
A package is a collection or code group in Perl. Meanwhile, a module in Perl is a package
defined in a file with the name “package” and the the extension .pm.
We can only define the package once in a program; whereas, more than one different module can
have the same name in a single code file.
Code
Perl package
A package name must always be at the start of a Perl program.
Consider the following code syntax with two subroutines (Car and Motorbike), and
a Vehicle package at the top of the code file.
# Package definition
package Vehicle;
sub Car{
print "This is a car subroutine!\n";
sub Motorbike{
print "This is a motorbike subroutine!\n";
Perl module
The following example shows how to import a package into our code file with the use keyword.
# Using package Vehicle
use Vehicle;
# Function Car of vehicle
Vehicle::Car();
# Function Motorbike of vehicle
Vehicle::Motorbike();
Perl BEGIN and END modules
Perl provides some built-in modules that include BEGIN and END. We use these modules to run
certain pieces of code at the beginning and end of a program.
The following code snippet includes the BEGIN and END modules. Upon looking at the code it
might seem that the print statement inside END would display first; but, if we run this code, it
will be displayed at the end.
The code below shows how this keyword works.
BEGIN{
print "Beginning of the program\n";
}
END{
print "Ending of the program\n";
}
print "Begin and End modules in Perl!\n";
Output
0.9s
Beginning of the program
Begin and End modules in Perl!
Ending of the program
5.8 WORKING WITH FILES
In Perl, a FileHandle associates a name to an external file, that can be used until the end of the
program or until the FileHandle is closed. In short, a FileHandle is like a connection that can be
used to modify the contents of an external file and a name is given to the connection (the
FileHandle) for faster access and ease.
The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which represent
Standard Input, Standard Output, and Standard Error devices respectively.
File Handling is usually done through the open function.
Syntax: open(FileHandle, Mode, FileName);
Parameters:
FileHandle- The reference to the file, that can be used within the program or until its closure.
Mode- Mode in which a file is to be opened.
FileName- The name of the file to be opened.
Also, Mode and FileName can be clubbed to form a single expression for open.
Syntax: open(FileHandle, Expression);
Parameters:
FileHandle- The reference to the file, that can be used within the program or until its closure.
Expression- Mode and FileName clubbed together.
The FileHandle is closed using the close function.
Syntax: close(FileHandle);
Parameters:
FileHandle- The FileHandle to be closed.
Reading from and Writing to a File using FileHandle
Reading from a FileHandle can be done through the print function.
Syntax: print(<FileHandle>);
Parameters:
FileHandle- FileHandle opened in read mode or a similar mode.
Writing to a File can also be done through the print function.
Syntax: print FileHandle String
Parameters:
FileHandle- FileHandle opened in write mode or a similar mode.
String- The String to be inserted in the file.
Different Modes in File Handling
Mode Explanation
“<“ Read Only Mode
Creates file (if necessary), Clears the contents of the File and Writes
“>” to it
“>>” Creates file (if necessary), Appends to the File
“+<“ Reads and Writes but does NOT Create
“+>” Creates file (if necessary), Clears, Reads and Writes
“+>>” Creates file (if necessary), Reads and Appends
Examples:
Consider a file [Link] containing the string “Welcome to GeeksForGeeks!!!” initially.
1. Mode = “<"
This is read-only Mode. This mode is used to Read the content line by line from the file.
#!/usr/bin/perl
# Opening a File in Read-only mode
open(r, "<", "[Link]");
# Printing content of the File
print(<r>);
# Closing the File
close(r);
2. Output:
3. Mode = “>”
This is write-only Mode. Original contents of the File are cleared once it is opened in this
Mode. It creates a new File with the same name, if one is not found.
#!/usr/bin/perl
# Opening File [Link] in Read mode
open(r, "<", "[Link]");
# Printing the existing content of the file
print("Existing Content of [Link]: " . <r>);
# Opening File in Write mode
open(w, ">", "[Link]");
# Set r to the beginning of [Link]
seek r, 0, 0;
print "\nWriting to File...";
# Writing to [Link] using print
print w "Content of this file is changed";
# Closing the FileHandle
close(w);
# Set r to the beginning of [Link]
seek r, 0, 0;
# Print the current contents of [Link]
print("\nUpdated Content of [Link]: ".<r>);
# Close the FileHandle
close(r);
4. Output:
5. Mode=”>>”
This is Append Mode. Original content of the File is not cleared when it is opened in this
Mode. This Mode cannot be used to overwrite as the String always attaches at the End. It
creates a new File with the same name, if one is not found.
#!/usr/bin/perl
# Opening File [Link] in Read mode
open(r, "<", "[Link]");
# Printing the existing content of the file
print("Existing Content of [Link]: " . <r>);
# Opening the File in Append mode
open(A, ">>", "[Link]");
# Set r to the beginning of [Link]
seek r, 0, 0;
print "\nAppending to File...";
# Appending to [Link] using print
print A " Hello Geeks!!!";
# close the FileHandle
close(A);
# Set r to the beginning of [Link]
seek r, 0, 0;
# Print the current contents of [Link]
print("\nUpdated Content of [Link]: ".<r>);
# Close the FileHandle
close(r);
6. Output:
7. Mode = “+<“
This is Read-Write Mode. This can be used to overwrite an existing String in File. It cannot
create a new File.
#!/usr/bin/perl
# Open [Link] in Read-Write Mode
open(rw, "+<", "[Link]");
# Print original contents of the File.
# rw is set to the end.
print("Existing Content of [Link]: ".<rw>);
# The string is attached at the end
# of the original contents of the file.
print rw "Added using Read-Write Mode.";
# Set rw to the beginning of the File for reading.
seek rw, 0, 0;
# Printing the Updated content of the File
print("\nUpdated contents of [Link]: ".<rw>);
# Close the FileHandle
close(rw);
8. Output:
9. Mode = “+>”
This is Read-Write Mode. The difference between “+<” and “+>” is that “+>” can create a
new File, if one with the name is not found, but a “+<” cannot.
#!/usr/bin/perl
# Opening File [Link] in Read mode
open(r, "<", "[Link]");
# Printing the existing content of the file
print("Existing Content of [Link]: " . <r>);
# Closing the File
close(r);
# Open [Link] in Read-Write Mode
open(rw, "+>", "[Link]");
# Original contents of the File
# are cleared when the File is opened
print("\nContents of [Link] gets cleared...");
# The string is written to the File
print rw "Hello!!! This is updated file.";
# Set rw to the beginning of the File for reading.
seek rw, 0, 0;
print("\nUpdated Content of [Link]: " .<rw>);
# Closing the File
close(rw);
10. Output:
11. Mode = “+>>”
This is Read-Append Mode. This can be used to Read from a File as well as Append to it. A
new File with same name is created, if one is not Found.
# Open [Link] in Read-Append Mode
open(ra, "+>>", "[Link]");
# Set ra to the beginning of the File for reading.
seek ra, 0, 0;
# Original content of the File
# is NOT cleared when the File is opened
print("Existing Content of the File: " . <ra>);
print "\nAppending to the File....";
# The string is appended to the File
print ra "Added using Read-Append Mode";
# Set ra to the beginning of the File for reading.
seek ra, 0, 0;
# Printing the updated content
print("\nUpdated content of the File: " . <ra>);
# Closing the File
close(rw);
12. Output:
13.
14. Redirecting Output
15.
Output can be redirected away from the Console and into a file using the select function.
16. Syntax: select FileHandle;
Parameters:
FileHandle – FileHandle of the File to be selected.
Steps:
Open a FileHandle to write i.e. “>”, “>>”, “+<“, “+>” or “+>>”.
Select the FileHandle using select function.
Now, anything that is printed using the print function is redirected to the File.
Example:
# Open a FileHandle in Write Mode.
open(File, ">", "[Link]");
# This sets File as the default FileHandle
select File;
# Writes to File
print("This goes to the File.");
# Writes to File
print File "\nThis goes to the File too.";
# This sets STDOUT as default FileHandle
select STDOUT;
print("This goes to the console.");
# Close the FileHandle.
close(File);
Output in the Console:
Contents of [Link]:
Original File:
Updated File: