presentation

System Administration
Introduction to Scripting, Perl
Session 4 – Sat 17 Nov 2007

References:


chapter 1,
The Unix Programming Environment, Kernighan
& Pike,
ISBN 0-13-937681-X;
Perl man pages
Albert Lingelbach, Jr.
[email protected]
1
Review









Scripts; perl; syntax: #comment, statement;
Scalar $variables
Special operators: = .
Math operators: + - * /; precedence,
associativity
Numerical comparisons: == < > <= >= !=
String comparisons: eq ne lt gt le ge
Control flow: if, while, for
Boolean logic: && || !
Subroutines, arguments/parameters,
functions
2
backquotes



it is often necessary to execute a command
and capture the results (standard output)
sh and perl use the same syntax for this;
enclose the command in backquotes (`,
usually in the upper left of the keyboard) and
assign the result to a variable
example:
$userid = `who am i`;
print $userid;
3
Recursive functions


"recursion" is a way of defining a function in
terms of itself and a base case
for example, the fibonacci series is defined
as:




the first fibonacci number is 0
the second fibonacci number is 1
every other fibonacci number is the sum of the
previous two
thus the fibonacci series begins:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...
4
Recursive functions continued

exponentiation (xy) can be defined
recursively:
# return x ^ y
sub power {
my $x = shift;
my $y = shift
if ($y == 1) {
return $x;
}
else {
return $x * power ($x, $y - 1);
}
}
5
Variable scope and recursion


Notice that each "call" of a recursive function
(or any function) gets its own copy of
variables declared with "my"
It can be helpful to trace through the "call
stack" to watch the variables as they change:
Call #
1
2
3
4
$x
2
2
2
2
$y
4
3
2
1
result
16
8
4
2
6
Variable Scope





my indicates that the variable has "local"
scope
without my, variable has "global" scope
local scope means the variable is defined
only within the enclosing braces
global scope means the variable is defined
everywhere, unless overridden by a local
version
this is useful for modularity
7
Variable Scope Example

example
sub mysub {
print "x = $x\n";
print "y = $y\n";
my $x = 7;
$y = 23;
print "x = $x\n";
print "y = $y\n";
}
# try moving this before sub
my $x = 3;
$y = 17;
print "x = $x\n";
print "y = $y\n";
mysub;
print "x = $x\n";
print "y = $y\n";
8
Exercises


Review session 2 exercises
Review session 3 exercises
9
Next Up



Arrays
Hashes
Regular Expressions
see perl man pages for details
man -M /usr/perl5/man perlintro
10