Azure Monitor & Application Insight to monitor Infrastructure & Application
perl_lessons
1. Perl Tutorial
Pablo Manalastas <pmanalastas@ateneo.edu>
LEARNING PERL
2. Numbers
● Numbers are double precision floating point
values (double in C)
3, 1.5, 2.7e8, 2_427_132_115,
0577, 0xf3ab, 0b1110001011
● Numeric operations
Add (+), subtract (), negate (), multiply (*),
divide (/), modulus (%)
3 + 4.2, 2.3e4*6.2523, 10%4
3. Strings
● Can be any length & can contain any characters
● Singlequoted strings
'Pablo de Gracia, Jr.'
'The winter of our discontent.'
'Queen's Jewels'
# the single quote ' is specified as '
'The backslash is special'
# the backslash is specified as
4. Strings
● Doublequoted strings
”against earth's flowing breast”
“I am called ”handsome” by some”
“I came.nI saw.nI conquered.n”
“Tabtseparatedtentriesthere”
● String concatenation
“Hello ” . “worldn”
● String repetition
“maganda ” x 3
5. Autoconversion: Numbers & Strings
● Arithmetic operations (+,,*,/,%) convert strings
to numbers
“12plus2” + “3” # gives the number 15
● String operation (.) converts numbers to strings
“XJW” . 24*5 # gives the string “XJW120”
6. Variables
● Variable names
[$@%][AZaz_][09AZaz_]*
● Scalar variables, name starts with $
– Holds one value (scalar value)
– Examples:
$daily_rate = 350.00;
$horse_name = “Heaven's Pride”;
$monthly_pay = $daily_rate * 22;
8. Output Using “print”
● Write output to stdout using print
print “Hello, world!n”;
print “The answer is ” . 350 * 6 .
“n”;
print “The answer is ”, 350 * 6,
“n”;
9. Interpolation
● Interpolation: the replacement of a scalar
variable by its value in a double quoted string or
when occuring alone
● Examples
$meal = 'beef steak';
print “Juan ate $mealn”;
print “I like $meal for dinnern”;
print “Juan's dinner is “ . $meal;
print “Juan's dinner is “, $meal;
10. Delimiting the Variable Name
● Use { } to delimit the variable name to be
interpolated
● Examples
$what = 'steak';
print “I love all kinds of ${what}sn”;
print “I love all kinds of $what”, “sn”;
print “Prime rib is the $what of ${what}sn”;
12. Boolean Values
● undef, number zero (0), string zero ('0'), the
empty string (''), are all false. Undef designates
a variable with no value assigned yet.
● nonzero numbers (like 1) and nonempty
strings (except '0') are all true.
● Examples
$bool1 = 'Fred' lt 'fred';
$bool2 = 'fred' lt 'Fred';
print $bool1; # prints 1 for true
print $bool2; # empty string for false
13. If Control Structure
● Syntax
if( condition ) { truepart; } else { falsepart; }
● Example
$disc = $b*$b – 4.0*$a*$c;
if( $disc >= 0.0 ) {
print “Real rootsn”;
} else {
print “Complex rootsn”;
}
14. Reading One Line from Stdin
● Use <STDIN> to read one line from standard
input, usually the console keyboard
● Examples:
print “Enter first name: “;
$fname = <STDIN>;
print “Enter last name: “;
$lname = <STDIN>;
chomp($fname);
chomp($lname);
print “Your name: $fname $lnamen”;
15. The chomp() Function
● chomp() removes a trailing newline 'n' from the
string value of a variable
● Version2 of program:
print “Enter first name: “;
chomp($fname = <STDIN>);
print “Enter last name: “;
chomp($lname = <STDIN>);
print “Your name: $fname $lnamen”;
16. While Control Structure
● Syntax:
initialization;
while ( condition ) {
statements;
reinitialization;
}
● Example:
$i = 1;
while($i <= 10) {
print “Counting $in”;
++$i;
}
17. UNDEF
● If an undefined variable is used as a number,
undef is like zero (0). If used as a string, undef
is like the empty string ('')
● If $x is undefined, the following are allowed:
$x += 2;
$x .= 'bye';
● If $x has a value, then
$x = undef;
makes $x undefined
18. The defined() Function
● The <STDIN> operation may return the value
undef when there is no more input, such as at
endoffile
● The function defined() can test if <STDIN> read
one line of input from standard input.
● Example
while(defined($line = <STDIN>)) {
print “You typed: $line”;
}
print “No more inputn”;
19. Exercises
● Write a Perl program that reads lines of input
from <STDIN>, and prints each line read. Stop
when the line that is read is 'Done' (without the
quotes).
● Write a Perl program that reads the values of
three variables $num1, $oper, and $num2 from
<STDIN>. If the value of $oper is one of the
strings 'plus', 'minus', 'times', or 'over', the
program should carry out the indicated
operation on $num1 and $num2.
20. Lists & Arrays
● List: an ordered collection of scalar values. The
index is the position of a scalar value in the list.
The index runs from 0 to (n1), where n is the
size of the list. An array is a variable that
contains a list, and starts with a @sign
● Example:
@quals
@friends
21. Initializing Arrays with Literal Values
● An array may be initialized with values in
parentheses ( ). Example:
@propty = ('Pablo', 62, 'male',
undef);
Here, the array is @propty, and the values in
the list are:
$propty[0] is 'Pablo'
$propty[1] is 62
$propty[2] is 'male'
$propty[3] is undef #civil status
22. Values May All Be Same Type
● All list values may be the same type
@friends = ('Pablo', 'Jose',
'Juan', 'Mario', 'David');
Here, the array is @friends, and the values in
the list are:
$friends[0] is 'Pablo'
$friends[1] is 'Jose'
$friends[2] is 'Juan'
$friends[3] is 'Mario'
$friends[4] is 'David'
23. Values of Array Indices
● Any value, variable, or expression, whose value is
integer or can be converted to integer can be used as
index.
● Example:
$ndx = 2.5;
$friends[$ndx+1] is $friends[3]
● $#friends is the value of the last index of array
@friends, which is 4.
● $friends[$#friends+10] = 'Carlos';
adds element 'Carlos' at index 14, the 15th element.
Values at index 5 to 13 will be undef.
24. Initializing Array with Literal Values
● @arr = ( );
@arr = (5..10, 17, 21);
@arr = ($a..$b);
@arr = qw/ Pablo Jose Mario /;
@arr = qw! Pablo Jose Mario !;
@arr = qw( Pablo Jose Mario );
@arr = qw{ Pablo Jose Mario };
@arr = qw< Pablo Jose Mario >;
25. Interpolate Arrays/Values in Strings
● If @arr is an array, then array @arr and list
value $arr[k] will be interpolated (evaluated)
when placed inside double quoted strings
● Example interpolating arrays
@arr = (5..7);
print “Four @arr eightn”;
# will print Four 5 6 7 eight
● Example interpolating list values
@toy = ('toycar', 'toyrobot',
'toygun');
print “I have a $toy[2] at homen”;
26. pop( ) Function
● pop() removes the rightmost list value from an
array
● Example:
@stk = (5..9);
$a = pop(@stk);
# remove 9 leaving 5..8, $a = 9
$b = pop @stk;
# remove 8 leaving 5..7, $b = 8
pop @stk; # remove 7 leaving 5..6
27. push() Function
● push(): adds new rightmost values to the list of
an array
● Example:
@stk = (5..8);
push(@stk, 0); # now (5,6,7,8,0)
push @stk, (1..3);# now (5,6,7,8,0,1,2,3)
@stk2 = qw/ 10 11 12 /;
push @stk, @stk2;
# now (5,6,7,8,0,1,2,3,10,11,12)
28. shift() and unshift()
● shift() is like pushing new first values, unshift()
is like popping the first value. These operations
are done on the leftmost end of the array.
● @stk = (5..9);
shift(@stk, 4); # now (4..9)
shift @stk, (1..3); # now (1..9)
$a = unshift @stk;
# remove 1 leaving (2..9), $a = 1
29. foreach Control Structure
● Syntax: foreach $var (@arr) { body; }
● Example: form the pural form of each fruit:
@fruits = qw/mango banana durian/;
foreach $fr (@fruits) {
$fr .= 's';
}
print “@fruitsn”;
30. Perl's Default Variable: $_
● If you omit $var in a foreach loop, you can refer
to this variable using $_
foreach (1..10) {
$sum += $_;
}
print “Total of 1..10 is $sumn”;
● If you omit $var in a print statement, the value of
$_ will be printed.
$_ = “Today is Saturdayn”;
print;
31. reverse() and sort()
● reverse(@arr) reverses the order of values in
the list
@fruits = qw/mango papaya chico/;
@revfr = reverse(@fruits);
@fruits = reverse(@fruits);
● sort(@arr) sorts the values in the list in
increasing lexicographic order, or string order,
not numeric order
@fruits = qw/mango papaya chico/;
@sfruits = sort(@fruits);
@rfruits = reverse sort @fruits;
32. Forcing scalar() Context
● If you want to use an array @arr in a scalar
context (for example, get the number of
elements in the list), use the function scalar()
@fruits = qw/mango banana orange/;
print “Favorite fruits: @fruitsn“;
print “My favorite fruits are “,
scalar(@fruits), “ in alln”;
33. <STDIN> as List or Scalar
● $line = <STDIN>;
reads one line from <STDIN>
● @lines = <STDIN>;
reads the entire file <STDIN> until endoffile
and assigns each line as an element of the
array @lines. If file is big, @lines may use up a
huge amount of memory. The endoffile of
<STDIN> is indicated by typing ControlD in
Unix.
35. Exercises
● Write a program that reads from <STDIN> a set
of numeric values, one per line, and computes
the mean and variance of these values. If N is
the number of values, then
mean = (sum of all values) / N;
variance =
(sum square(each value – mean)) / N;
● Write a program that reads lines from <STDIN>,
sorts these lines in reverse alphabetical order,
prints the lines, and prints the total number of
lines.
36. Hashes
● A hash is a list of keyvalue pairs. The variable
name starts with %
%age = (“Pablo”, 62, “Karen”, 23,
“Paul”, 33);
Here the key “Pablo” has value 62, the key
“Karen” has value 23, and the key “Paul” has
value 33.
● Accessing a hash by key
$age{“Paul”} gives 33
$age{“Karen”} gives 23
38. Using a Hash
● %lname = (“Pablo”=>”Manalastas”,
“Rojo”=>”Sanchez”,
“Joy”=>”Fernando”);
print “Enter first name: “;
chomp($fname = <STDIN>);
print “Last name of $fname is “,
$lname{$fname}, “n”;
39. Keys & Values
● %month = (1=>”January”,
2=>”February”,
3=>”March”, 4=>”April”, 5=>”May”);
● @k = keys %month;
# @k is the array of keys only
● @v = values %month;
# @v is the array of values only
40. each() & exists()
● %month = (1=>”January”,
2=>”February”,
3=>”March”, 4=>”April”, 5=>”May”);
● To access each (key,value) pair:
while(($key,$val) = each %month) {
print “$key => $valn”;
}
● To check if a value exists for a key
If( exists $month{13}) {
print “That is $month{13}n”;
}
41. Hash Element Interpolation
● %month = (1=>”January”,
2=>”February”,
3=>”March”, 4=>”April”, 5=>”May”);
● Can interpolate each element
print “First month is $month{1}n”;
● Not allowed
print “The months are: %monthn”;
42. Exercises
● Write a program that reads a series of words
(with one word per line) until endofinput, then
prints a summary of how many times each word
was seen.
● Write a program that prompts for month number
(112), day number (131), and year (1900
2008), and display the inputs in the form
“MonthName day, year” (without the quotes).
43. Subroutines
● Userdefined functions that allow the
programmer to reuse the same code many
times in his program
● Subroutine name starts with &, in general
● Defining a subroutine
sub subName {
subBody;
}
44. Example Function
● Defining a function:
sub greet {
print “Hello!n”;
}
● Using the function:
&greet;
45. Passing Arguments
● If the subroutine invocation is followed by a list within
parenthesis, the list is assigned to special variable @_
within the function
● Example
&greet(“Pablo”, “Jose”, “Maria”);
You can use the arguments as follows:
sub greet {
for each $name in (@_) {
print “Hello $name!n”:
}
}
47. Exercises
● Write a function that returns the product of its
arguments
● Write a function that accepts two arguments n
and d, returns a list of two numbers q and r,
where q is the quotient of n and d, and r is their
remainder
● Write a function that, given any number n as
argument, prints the value of that number in
words, as in a checkwriter.