Lecture Notes 14
Lecture Notes 14
Lecture Notes 14
CS 3377
Lecture Notes 14
1
Reading for Week 13-14
Chapter 11 of A Practical Guide to
Linux® Commands, Editors, and Shell
Programming, Third Edition. Mark G.
Sobell.
◼ Chapter 11: The Perl Scripting Language
2
PERL
Comments with #
PERL Basics
Print command for writing to standard
output
◼ print “Hello, world!";
◼ Formatting with printf
◼ Close to C printing
You can try out your first PERL program
◼ Print Hello, world! and list files in
your working directory
#!/bin/perl –w
print “Hello, world!\n";
system("ls *");
PERL Basics
How to run a PERL program?
◼ Like shell scripts, make file executable and run
◼ $ ./helloworld.pl
◼ How do you make file executable?
Scalar variables
List variables
Push and pop
Shift and unshift
Reverse and Splice
Hash, keys, values, each
Scalar Variables
They should always be preceded with
the $ symbol. $name = “John”;
Not necessary to declare the variable
first and then use.
There are no datatypes to declare.
The scalar variable means that it can
store only one value and it can be of any
type.
What’s difference with bash variables?
Scalar Variable
$name = “John”;
print "$name \n";
The output on the screen will be John.
Default values for all variables is undef,
equivalent to null.
Scalar Variables
Experiment with scalar variables
$ cat string1.pl
#!/bin/perl -w
$string="5"; # $string declared as a string, but it will not matter
print '$string+5\n'; # Perl displays $string+5 literally because of
# the single quotation marks
print "\n$string+5\n"; # Perl interpolates the value of $string as a string
# because of the double quotation marks
print $string+5, "\n"; # Lack of quotation marks causes Perl to interpret
# $string as a numeric variable and to add 5;
# the \n must appear between double quotes
10
Scalar Variables
$ cat scalars1.pl
#!/bin/perl -w
$name = "Sam";
$n1 = 5; $n2 = 2;
print "$name $n1 $n2";
print "$n1 + $n2";
print '$name $n1 $n2';
print $n1 + $n2, " ", $n1 * $n2;
print $name + $n1;
11
List Variables
They are like arrays. It can be considered
as a group of scalar variables.
List variables are always preceded by the
@symbol
◼ @names = (“John",“Lisa",“James");
◼ As in C, the index starts from 0.
◼ If want the second member of the list,
you can access it as $names[1]
◼ Each element is a scalar hence $
◼ @names will give you the length of the
list i.e., 3
◼ $#names as the index of the last
element in the array named array. 12
List Variables
$ cat arrayvar1.pl
#!/usr/bin/perl -w
@arrayvar = (8, 18, "Sam");
print $arrayvar[1]; #18
print "@arrayvar[1,2]"; #18 sam
$ cat arrayvar2.pl
#!/usr/bin/perl -w
@arrayvar2 = ("apple", "bird", 44, "Tike",
"metal", "pike");
$num = @arrayvar2; #number of elements
print "Elements: ", $num, "\n"; #Elements: 6
13
List Variables
$ cat arrayvar3.pl
#!/usr/bin/perl -w
$v1 = 5; $v2 = 8;
$va = "Sam"; $vb = "uel";
@arrayvar3 = ($v1, $v1 * 2, $v1 * $v2, "Max", "Zach", $va . $vb);
print $arrayvar3[2], "\n"; # one element of an array is a scalar
print @arrayvar3[2,4], "\n"; # two elements of an array are a list
print @arrayvar3[2..4], "\n"; # a slice
print "@arrayvar3[2,4]", "\n"; # a list, elements separated by SPACEs
print "@arrayvar3[2..4]", "\n"; # a slice, elements separated by SPACEs
print "@arrayvar3\n"; # an array, elements separated by SPACEs
14
Shift, Push, Pop, and Splice
The shift function returns and removes
the first element of an array.
The push function adds an element to
the end of an array.
The pop function returns and removes
the last element of an array.
The splice function replaces elements of
an array with another array.
15
Push and Pop
@names = ("betty","veronica","tom“)
18
Hash, keys, and values
Hashes are like arrays but instead of
having numbers as their index they can
have any scalars as index.
Hashes are preceded by a % symbol.
◼ We can have %hash1 = ("A",1,"B",2,"C",3);
If we want to get the number of A we
have to print $rollnumbers{“A"}. This
will return the value of A.
Hash, Keys, and Values
%hash1 = ("A",1,"B",2,"C",3);
Here A is called the key and 1 is its
value.
Keys() returns a list of all of the keys of
the given hash.
Values() returns the list of all of the
values in a given hash.
20
Hashes
$ cat hash1.pl
#!/usr/bin/perl -w
$hashvar1{boat} = "tuna";
$hashvar1{"number five"} = 5;
$hashvar1{4} = "fish";
@arrayhash1 = %hashvar1;
print "@arrayhash1";
21
Hashes
$ cat hash2.pl
#!/usr/bin/perl -w
%hash2 = (
boat => "tuna",
"number five" => 5,
4 => "fish",
);
@array_keys = keys(%hash2);
say " Keys: @array_keys";
@array_values = values(%hash2);
say "Values: @array_values";
22
Each
Each function iterates over the entire
hash returning two scalar value the first
is the key and the second is the value
26
if…else
The if...else control structure is a
compound statement that is similar to
the bash if...then...else control
structure. It implements a two-way
branch using the following syntax:
27
if…else
$ cat ifelse.pl
#!/usr/bin/perl -w
print "Enter a number: ";
$num1 = <>;
print "Enter another, different number: ";
$num2 = <>;
if ($num1 == $num2) {
die ("Please enter two different numbers.\n");
}
if ($num1 > $num2) {
print "The first number is greater than the second number.\n";
}
else {
print "The first number is less than the second number.\n";
}
28
Comparison Operators
29
if…elsif…else
Similar to the bash if...then...elif control
structure, the Perl if...elsif...else control
structure is a compound statement that
implements a nested set of if...else
structures using the following syntax:
30
if…elsif…if
Rewrite previous example using elsif
if ($num1 > $num2) {
print "The first number is greater than the
second number.\n";
}
elsif ($num1 < $num2) {
print "The first number is less than the second
number.\n";
}
else {
print "Please enter two different numbers.\n";
}
31
foreach/for
This statement takes a list of values and
assigns them one at a time to a scalar
variable, executing a block of code with
each successive assignment.
◼ foreach/for $var (list) {}
$ cat foreach.pl
foreach $item ("Mo", "Larry", "Curly") {
print "$item says hello.";
}
If you do not specify var, Perl assigns
values to the $_ variable
foreach/for
$ cat foreacha.pl
foreach ("Mo", "Larry", "Curly") {
print "$_ says hello.";
}
foreach and for are synonyms
The second syntax for the foreach
structure is similar to the C for
structure:
foreach|for (expr1;expr2;expr3) {...}
33
foreach/for
$ cat ./foreach2.pl
#!/usr/bin/perl -w
print "Enter starting number: ";
$start = <>;
print "Enter ending number: ";
$end = <>;
print "Enter increment: ";
$incr = <>;
if ($start >= $end || $incr < 1) {
die ("The starting number must be less than the ending
number\n",
"and the increment must be greater than zero.\n");
}
40
PERL Random Numbers
Between 0 and 1
#!/bin/perl
$random_num = rand();
print $random_num "\n";
41
PERL random numbers
Between any two numbers
#!/bin/perl
$min = 50
$max = 100
$random_num = int(rand($max -$min)) + $min;
print $random_num "\n";
42
PERL User Inputs and Chomp
The chomp() function will remove (usually)
any newline character from the end of a
string.
#!/bin/perl
while (my $text = <STDIN>)
{ chomp($text);
print "You entered '$text'\n";
last if ($text eq '');
}
If you chomp an array, it will remove a newline
from the end of every element in the array.
43
Opening and Writing to a File
open(my $fh, '>>', 'report.txt');
Opens the file report.txt in the working
directory in append mode.
$fh is the file handle for this file
print $fh “Hello, world\n";
44