Perl Examples
Example 1:
This program is stored in file
perl-1#!/usr/bin/perl
# Comments are written by having
# as the first character of the line# Note the name of this program is perl-1
# To execute this program type:
perl perl-1# Note perl statements
end with semi colon(;).#As is the case with C and C++
\n means empty the buffer#
Execution of the program:
perl perl-1
How are you
Example 2:
The program is stored in file
perl-2#!/usr/bin/perl
print "Enter hexadecimal number: ";
# Following statement
assigns whatever typed from the keyboard i.e. the# standard input device
<STDIN> to the scalar variable answer. Notice that# a
scalar variable is a variable contains a single value. In other words# a variable which is not an array. A scalar variable(such as
$answer in# the next statement) is made of
$ sign followed by a name. A scalar# variable can have a
string or a numeric value.#
$answer=
<STDIN>;#
# The
hex in the following statement is a built-in function converts# the
hexa-decimal number to decimal numberExecution of the program:
perl
perl-2Enter hexadecimal number: 3B
59
Example 3:
The program is stored in file
perl-3#!/usr/local/bin/perl
-w#
#
Notice the option -w after perl provides the ability to execute the# program by writing its name only. Therefore
to execute this program all# all you have to do is to type
perl-3 . If option -w does not follow perl you have# to type perl perl-3 to execute perl-3 program
#
# perl like other shell programs
recognizes all four different types# of
quotes namely back quotes, double quotes, single quotes and back#
slash quote# The following statement executes date command and assigns its value
# to the scalar variable tday.
$tday =
`date`;# double quotes allow variable substitution
print " Welcome today date is $tday ";
# Do the following loop forever
Until a control c is typed to interrupt the programfor (
;;){
# Get the information from the user.
# Notice
my in the following statement tells perl that scalar variable#
$name is a local variable.my
$name = ""; # assign null as the value for scalar variable $name# Following while loop forces the user to enter
a non null namewhile
($name eq "" ) {print "Enter a non blank employee name: ";
$name =
<STDIN>;chomp
$name; # this commands removes the end line character}
end of while loopmy
$hours = 0;# repeat the loop until value greater than 0 is typed
while
($hours <= 0) {print "Enter number of hours greater than 0: ";
$hours = <STDIN>
; chomp $hours; # Notice 2 statements written on this line}
my
$rate = 0;while
($rate <= 0) {print "Enter rate per an hour greater than 0: ";
$rate = <STDIN>; chomp $hours;
}
# Find pay.
my
$pay = $hours * $rate;print " $name worked
$hours hours at rate $rate\n";# Notice the back slash quote
in-front of $pay makes the dollar sign# to be printed in-front of value of
$payprint "The pay for
$name is \$$pay \n";}
Execution of the program:
perl-3
Welcome today date is
Sun Mar 5 23:52:48 EST 2000Enter a non null employee name:
Linda BrownEnter number of hours greater than 0:
38Enter rate per an hour greater than 0:
10.50Linda Brown worked 38 hours at rate 10.50
The pay for Linda Brown is $399
Enter a non null employee name:
Jim SmithEnter number of hours greater than
0: 20Enter rate per an hour greater than 0
: 10Jim Smith worked 20 hours at rate 10
The pay for Jim Smith is $200
Enter a non null employee name:
% cat perl-4-list
#!/usr/local/bin/perl -w
# Declare an array months. Notice the character
@ before months. This# tells perl that months is an array.
#
my tells perl that this is a local variable. Perl 4 had "local"# Instead of "
my" to declare local variables. Perl 5 accepts both# my and local to declare local variables. It is recommended to use my.
# "
qw" (stands for quote word) makes perl to consider the entries# between parentheses to be quoted.
# Without
qw the above statement should be written as:#
my @months = ("JUNK" "Jan" "Feb" "March" "April" "May" "June" # "July" "Aug" "Sept" "Oct "Nov" "Dec");# The index of the array and list
starts at 0. As you see the following# Statement declares an array of size 13 and initializes its elements. The
# value of the first element $months[0] is Junk and the value of
# $months[12] is Dec.
#
my
@months = qw (JUNK Jan Feb March April May June July Aug Sept Oct Nov Dec);#
# Declare and initialize the value of scalar variable (that is non array
# variable) x to 0.
my
$x = 0;# Use the
for loop to print out the contents of the array.#
#Notice the
# after $ sign in-front of the array name month in the for#statement below. The
$#months is the index of the last element of the arrayfor
($x=0; $x <= $#months; $x++){
# Notice the $ in-front of months, That tells retrieve the value of months
print "Index[$x] =
$months[$x]\n";}
Following is the execution of
perl-4-litsExecution of the program:
perl-4-list
Index[0] = JUNK
Index[1] = Jan
Index[2] = Feb
Index[3] = March
Index[4] = April
Index[5] = May
I
ndex[6] = JuneIndex[7] = July
Index[8] = Aug
Index[9] = Sept
Index[10] = Oct
Index[11] = Nov
Index[12] = Dec
cat perl-4-v2
#!/usr/local/bin/perl -w
# Following statement declars an array ar. Numbers between 20 to 25 are
# assigned to its elements
my
@ar = (20..25);print "the elements of the array area:\n";
#The next statement prints all elements of the array. Notice no subscript
# after @ar
print "
@ar\n";# Assign the size of the array to scalar variable $n. In this case the
# value of $n will be 6.
$n=
@ar;print "\narray size is $n";
# Assign the index of the last element $#ar (in this case is 5) to the
# scalar variable $n2
$n2=
$#ar;print "\nthe index of the last elemn is $n2";
# Because the index of the first elemnt is 0, the size of the array equal
# to the index of the last elemnt + 1
$array_size=$n2 +1;
print "\narray size also is $array_size\n";
Execution of the program:
% cat perl-5
#!/usr/local/bin/perl -w
# File_input contain 5 numbers each on a line.
$Infile="File_input";
# This statement assigns file handler Infile to File_inputopen
(Infile);# Next statement declares Inarray as an array
and assigns the records of Infile to the array-elements@Inarray =<
Infile>;close
(Infile);#
# Next statement assigns the size of the array
to scalar variable $arsizemy
$arsize = @Inarray; # Note array name without subscript means the size of the array.print "number of elements in the array is: $arsize \n";
print "number of elements in the array is: ", $#Inarray
+ 1, "\n";foreach
$i (@Inarray) {print "
$i";}
Execution of the program:
% cat perl-5-v2
#!/usr/local/bin/perl -w
#define array @array and scalar variable index
my
(@array, $index);# Push the elements on the 'stack'
push
(@array, "Hello");push
(@array, "World!");# Print out the contents of the array using foreach loop.
foreach
(@array){
# Notice
$_ is a special variable for default input. perl has 50 special# variables. Also there are
English name for them. For example $$ is the# processor id. But if you use the English module (by having
use English;# as a statement in your program you can use English names.
}
# Print out the contents of the array via pop.
while
( $index = pop(@array) ){
print "Popping off stack: $index\n";
}
Execution of the program:
cat perl-6-stack
#!/usr/local/bin/perl -w
# Define variables.
my ($index, @mylist);
# Push the elements onto the stack.
push
(@myList, "you?");push
(@myList, "are");push
(@myList, "how");push
(@myList, "world!");push
(@myList, "Hello");while
($index = pop(@myList)){
print "Popping off stack:
$index\n";}
Execution of the program:
perl-6-stack
Popping off stack: Hello
Popping off stack: world!
Popping off stack: how
Popping off stack: are
Popping off stack: you?
cat perl-7-each
#!/usr/local/bin/perl -w
# Create an Associative array call it mySchools. Notice character "
%"# before the name makes the name to be an Associative array.
#
Associative arrays (also known as hash arrays) do not have beginning# and end. Keys reference the individual values of the array elements.
# Notice the ke and its associated value either separated by
=> or a comma ,# Notice the key Kurdistan _ High School and its associated value Erbile are separated by a comma
my
%mySchools = ("Kurdistan_Elm" => Rawanduz, "Kurdistan _ High School",Erbile, "Iraq"
=> "Baghdad University", "US - ST. Louis" => "Washington University");# The following statement displays the value of the array
# element referenced by key Kurdistan_Elm. Notice that the key is in braces
# Notice curly parenthesis around key
my
($key, $value);# Print out the contents of the hash.
while
(($key, $value) = each %mySchools){
}
Execution of the program:
Bellow is the execution of the program
perl-7-each
The school identified by key Kurdistan_Elm is: Rawanduz
Key: Kurdistan_Elm Value: Rawanduz
Key: Kurdistan _ High School Value: Erbile
Key: Iraq Value: Baghdad University
Key: US - ST. Louis Value: Washington Universi
cat perl-8-key-2
#!/usr/local/bin/perl -w
# Create an Associative array call it mySchools. Notice character "
%" before the name.my
%mySchools = ("Kurdistan -Elm" => Rawanduz, "Kurdistan _ High School",Erbile, "Iraq"
=> "Baghdad University", "US - ST. Louis" => "Washington University");# declare
key as a scalar variable. Notice both word keys and values are reserved# words in perl, but
key and value are not.my
$key;# Print out the contents of the hash. Notice the sort keys.
for
$key (sort keys %mySchools){
}
Execution of the program:
Bellow is the execution of the program
perl-8-key-2
Key: Iraq Value: Baghdad University
Key: Kurdistan -Elm Value: Rawanduz
Key: Kurdistan _ High School Value: Erbile
Key: US - ST. Louis Value: Washington University
cat perl-9-value
#!/usr/local/bin/perl -w
# Create an Associative array call it mySchools. Notice character "%" before the name.
my %mySchools = ("Kurdistan -Elm" => Rawanduz, "Kurdistan _ High School",
Erbile, "Iraq" => "Baghdad University", "US - ST. Louis" => "Washington University");
my $value;
# Print out the contents of the hash. Notice the
sort in-front of valuesfor
$value (sort values %mySchools){
}
Execution of the program:
Bellow is the execution of the program
perl-9-value
Value: Baghdad University
Value: Erbile
Value: Rawanduz
Value: Washington University
cat perl-10
#!/usr/local/bin/
perl -w# To end the execution of this program type control c
# Do this forever
for (
;;){
# Get the information from the user.
my
$num1 = <STDIN>; chomp $num1;my
$num2 = <STDIN>; chomp $num2;# Perform some basic operations.
my
$sum = $num1 + $num2;my
$diff = $num1 - $num2;if
($num1 = = $num2)if
($num1 < $num2){
print "<$num1> is numerically less than <$num2>\n"; }if
($num1 > $num2){
print "<$num1> is numerically greater than <$num2>\n"; }}
Execution of the program:
Bellow is the execution of the program
perl-10
Enter a number: 30
Enter another number: 60
The sum of 30 and 60 is 90
The difference of 30 and 60 is -30
<30> is numerically less than <60>
Enter a number:
Cat perl-10-v2
#!/usr/local/bin/perl -w
# To end the execution of this program type control c
# Do this forever
# The following statement is a label, which includes an infinite
for loopFOREVER_LOOP
:for
(;;){
# Get the information from the user.
my
$num1 = <STDIN>; chomp $num1;# Exit from
FOREVER_LOOP if 99999 is typelast
FOREVER_LOOP if $num1 == 99999;my
$num2 = <STDIN>; chomp $num2;# Perform some basic operations.
my
$sum = $num1 + $num2;my
$diff = $num1 - $num2;prin
t "The difference of $num1 and $num2 is $diff\n";if
($num1 = = $num2){
print "Both numbers are equal.\n";
}
if ($num1 < $num2)
{
print "<$num1> is numerically less than <$num2>\n";
}
if ($num1 > $num2)
{
print "<$num1> is numerically greater than <$num2>\n";
}
}
Execution of the program:
Bellow is the execution of the program
perl-10-v2
To stop the program type 99999
Enter a number: 40
Enter another number: 40
The sum of 40 and 40 is 80
The difference of 40 and 40 is 0
Both numbers are equal.
To stop the program type 99999
Enter a number: 99999
cat perl-10-annonymous-array
#!/usr/local/bin/perl -w
# Create the anonymous array reference.
# Notice anonymous arrays are created by enclosing a set of values
# between
[ and ] without having any name to the arrays.my $arrayRef =
[[1,2,3,4], 'a', 'b', 'c', 'd', 'e', 'f'];# Print out some of the array
# Remember the dot
. is for concatinationprint $arrayRef->[
0][0] . "\n";print $arrayRef->[
0][2] . "\n";print $arrayRef->[
0][1] . "\n";print $arrayRef->[
0][3] . "\n";print "reference to the first element :";
# The following statement prints the reference to the first element,
# because the first element itself is an array.
print $arrayRef
->[0] . "\n";# print all elements of the first array
for
($i=0; $i<4; $i++){
print $arrayRef->[0][
$i] ." " ;}
#print all elements of the anonymous array arrayRef
print "\narrayRef elements are:\n";
for
($i=0; $i<8; $i++){
print $arrayRef
->[$i] . " " ;}
print "\n";
Execution of the program:
Bellow is the execution of the program
perl-10-annonymous-array
1
3
2
4
reference to the first element :ARRAY(0x140002080)
1 2 3 4
arrayRef elements are:
ARRAY(0x140002080) a b c d e f
Example -11
cat grade-perl
#!/usr/local/bin/perl -w
# open a file called
grades and assign GRADES as the file handle for it# if the file does not exist the program calls function
die that# prints the message and terminate the program. Note
or is a short circuit# logical operator. That is if first operand is executed successfully the
# rest of the command is skipped.
# The value of
$! will contains the error message if it can not open the file# Notice
< in grades indicates to open grades as an input fileopen
(GRADES, "<grades") or die "can not open grades: $!\n";# <GRADES> returns a string value, or it fails when there are no
# more lines in the file. On the failure,
$line is undefined. the# "
defined()" function returns true if $line has a good value,# and returns
false if $line is undefined. While statement requires# true or false value,
defined stands for true and undefined is for falsewhile (
defined($line = <GRADES>) ) {# Fields of $line are separated by spaces
(
$student, $grade) = split (" ", $line);# Notice the
period before = and after $grade means concatenation.# The following statement makes
grades to be an associate array (%grades),# The
key will be $student, because $Student follows $grades and# is enclosed in
curly braces$grades
{$student} .= $grade . " ";}
# End of while loopforeach
$student (sort keys %grades) {# number of grades of a student will be assigned to scalar variable
# $scores and $total will contains sum of grades of a student
$scores = 0;
$total = 0;
# The next statement creates an ordinary array grades (@grades). Thus
# thus we have associate array %grades and ordinary array @array'
@grades =
split (" ", $grades{$student});# Following foreach loop finds number of grades and sum of grades for
# a student
foreach
$grade (@grades) {$total += $grade;
$scores++;
}
# End foreach loop# Find the average grade for a students
$average = $total / $scores ;
print "$student: $grades
{$student}\tAverage: $average\n";}
Execution of the program:
Following is the content of grades file
cat grades
cat grades
Noel 25
Ben 76
Clem 49
Norm 66
Chris 92
Doug 42
Carol 25
Ben 24
Clem 51
Norm 66
Clem 92
Noel 75
Noel 80
Clem 38
Bellow is the execution of the program
grade-perl
Ben: 76 24 Average: 50
Carol: 25 Average: 25
Chris: 92 Average: 92
Clem: 49 51 92 38 Average: 57.5
Doug: 42 Average: 42
Noel: 25 75 80 Average: 60
Norm: 66 66 Average: 66
Example -11-V2
In this version unless is used with die function and $#grades +1 to find number of elements in an array. The rest of the program is identical to the previous version.
cat grade-perl-v2
#!/usr/local/bin/perl -w
# This version of grades use die and unless statements
# The following statement display message can not open grades unless
# grades file is exist.
die
"can not open grades: $!\n"unless
(open(GRADES, "<grades"));while ( defined($line = <GRADES>) ) {
($student, $grade) = split (" ", $line);
$grades{$student} .= $grade . " ";
}
foreach $student (sort keys %grades) {
$total = 0;
@grades = split (" ", $grades{$student});
foreach $grade (@grades) {
$total += $grade;
}
#Notice $#grades is the index of the last element of the array
$average = $total / (
$#grades + 1) ;print "$student: $grades{$student}\tAverage: $average\n";
}
cat perl-12
#!/usr/local/bin/perl -w
# Do this forever
for
(;;){
# Get the information from the user.
print "Enter a word: ";
my
$word1 = <STDIN>; chomp $word1;my
$word2 = <STDIN>; chomp $word2;# Perform some basic operations.
if
($word1 eq $word2){
print "The two phrases are equivalent.\n";
}
if
($word1 lt $word2){
print "<$word1> is alphabetically less than <$word2>\n";
}
if
($word1 gt $word2){
print "<$word1> is alphabetically greater than <$word2>\n";
}
}
Execution of the program:
Bellow is the execution of the program
perl-12
Enter a word: Jim
Enter another word: Kim
<Jim> is alphabetically less than <Kim>
Enter a word:
perl-13-ref
#!/usr/local/bin/perl -w
# Set up the data types.
my
$scalarVar = "How are you doing?";my
@arrayVar = qw (January February March April May);my
%hashVar = ('Pay-type' => 'regular', 'Rate' => 23.5, 'Union' => No);# Reference variables are created by having
\ in-front of the variables# Create the references
my
$scalarRef = \$scalarVar;my
$arrayRef = \@arrayVar;my
$hashRef = \%hashVar;# Notice reference variables are
pointers in languages such as C or C++# Print out the references.
# To create
de-reference:# Put
$ in-front of reference variable to a scalar variable.# Put
@ in-front of reference variable to an array.#Put
% in-front of reference variable to a hash array.# Print the content of variable referenced by scalar variable.
print "scalar value:
$$scalarRef \n";#Print the content of the elements of the array referenced by
# reference variable
my $month;
for
$month (@$arrayRef){
print "Month: $month \n";
}
#print the content of the elements of the hash array referenced by
# reference variable
my $hashelement;
for $hashelement (
%$hashRef){
print " $hashelement \n";
}
print "Sorted keys:\n";
for $hashelement (
sort keys %$hashRef){
print " $hashelement\n";
}
print "Sorted values:\n";
for $hashelement (
sort values %$hashRef){
print " $hashelement\n";
}
Execution of the program:
Bellow is the execution of the program
perl-13-ref
SCALAR(0x140010160)
ARRAY(0x1400101b0)
HASH(0x140010210)
scalar value: How are you doing?
Month: January
Month: February
Month: March
Month: April
Month: May
Union
No
Pay-type
regular
Rate
23.5
Sorted keys:
Pay-type
Rate
Union
Sorted values:
23.5
No
regular
How To Simulate Case-Switch statements in perl
perl does not have case or switch statements. However these statements can be simulated in many ways in perl. Following is an example of simulating a case statement by creating a label. This example is taken from your text book on page 198.
cat perl_case_simulate-2
#!/usr/local/bin/
perl -w# This program to be executed as:
#
perl_case_simulate /A/C /HELP /B /Foo/Bar:3$Args = "";
# assign null to scalar variable $Args# Notice
@ARGV is a reserved array that contains all arguments submitted#
with the program. In this case @ARGV[0]= /A/C , @ARGV[1]= /HELP ,#
@ARGV[2]= /B , and @ARGV[3]= /Foo/Bar:3# Notice arguments were seprated by spaces
# Notice in the Following while loop
@ARGV is size of the# of the array
@ARGV and the while loop is executed as long as# the size of the array is greater than 0.
while
(@ARGV) {#Usually to search for a pattern the pattern is enclosed
#
between / and / . Notice the character m in the expression =~ m%^/%# tells
perl that the next character is (that is %) used for search instead of usual /#
Character ~ tells match the expression on the left of = sign$ARGV[0] =
~ m%^/% || last;#
Notice shift uses @ARGV by defaut$Args .= shift;
# Following are the values of $Args during the execution of while loop
# At the end of first iteration: value of
$Args is /A/C# At the end of second iteration: value of
$Args is /A/C/HELP# At the end of third iteration: value of
$Args is /A/C/HELP/B# At the end of final iteration: value of
$Args is /A/C/HELP/B/Foo/Bar:3}
# end of while loop# The following statement deletes the first
/ from $Args# Notice character
s stands for subsitute$Args =~
s%^/%%;# now value of
$Args is A/C/HELP/B/Foo/Bar:3foreach
$Arg (split("/",$Args)) {#Begun foreach# the expression
\w+ takes all alphanumeric characters until# a non alphanumeric is found. Thus the string will be
A$Arg =~ /\
w+/;#
Notice $& is the string from the last successful pattern match$_ =
$&;CASE:
{ #begin case#
case A/
^A$/ && do {print "Found A\n";
last
CASE;}
;#
case B/
^B$/ && do {print "Found B\n";
last
CASE;}
;#
case C/^C
$/ && do {print "Found C\n";
last CASE;
}
;#
case HELP/
^HELP$/ && do {print "Found HELP\n";
last
CASE;}
;#
case None of the aboveprint "Unknown option found: /$Arg\n";
}
# End CASE}
# End foreach