Download presentation
Presentation is loading. Please wait.
Published byDominick Harper Modified over 9 years ago
1
1 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. alingelb@yahoo.com
2
2 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
3
3 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;
4
4 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,...
5
5 Recursive functions continued exponentiation (x y ) 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); }
6
6 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:
7
7 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
8
8 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";
9
9 Exercises Review session 2 exercises Review session 3 exercises
10
10 Next Up Arrays Hashes Regular Expressions see perl man pages for details man -M /usr/perl5/man perlintro
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.