esa 2009/2010 eelco schatborn eelco@os3 · perl introduction i \practical extraction and report...
TRANSCRIPT
ESA: Perl
Today:
1. Perl introduction
2. Basic Perl: types, variables, statements, . . .
3. Object Oriented Perl
4. Documentation
2/ 33
Perl Introduction
I “Practical Extraction and Report Language”?
I Developed by Larry Wall, as systemadministrator at NASA, in the late 1980s
I Created as a way to make report processingeasier.
I It’s an interpreted language, but can becompiled as well
I Is now being used for:I System administration automationI Glue between systems, conversionI CGI backend for websitesI Much more. . .
3/ 33
Simple Perl
A simple program to start with:
#!/usr/bin/perlprint "Hi there!\n";print "This is a very";print "\tsimple program.\n";
4/ 33
Numbers
simple numbers as per usual:
I decimal: 12, -17, 255 . . .
I octal, start with 0: 015, -023, 0777 . . .
I hexadecimal, start with 0x: 0xc, -0x11, 0XfF, . . .either case allowed for the x or hex digits abcdef.
floating point numbers:
I “one and a quarter”: 1.25
I “7.25 times 10 to the 45th power”: 7.25e45.
I “negative 12 times 10 to the -24th”: -12e-24.
5/ 33
Strings
I Escape sequences represent special characters:\n, \t, . . .
I Only in double quoted (‘"’) strings
I For verbatim strings use single quotes (‘’’)
Perl: print "Hi there! \n \t It’s me.\n";print ’And me \n \t as well!’;
output: Hi there!It’s me.
And me \n \t as well!
6/ 33
Variables
I Three different types of variables:scalars, arrays and hashes
I Start with the dollar (‘$’), at (‘@’) or percentage (‘%’) sign,depending on the type of variable
I Variable names are a punctuation character, a letter orunderscore, and one or more alphanumeric characters orunderscores.
7/ 33
Scalar variables
I Start with the dollar (‘$’) sign.
I Can be a number or a string (or an object reference)
I The usual operators apply:
+, -, *, /, =, +=, -=, *=, /=, ++, --
I Perl automatically converts between numbers and strings.
$n = 8 + "2" → $n holds "10"
I But concatenation of strings using a period ‘.’
$n = 8 . "2" → $n holds "82"
8/ 33
Array variables (1)
I Start with the at (‘@’) sign.
I Arrays represent ordered lists of scalars.
I Definition using parenthesized, comma delimited lists:@numbers = ( 1, 2, 4, 8, 16 );@strings = ( "one", "two", "3" );
I The index of an array starts at 0, not 1
I Processing single items as a scalar using ‘[’ and ‘]’:print $strings[1]; → prints "two"$strings[1] = "2"; → we changed @strings
9/ 33
Array variables (2)
I Arrays can be created using scalar assignment:$names[0] = "Eelco";→ creates @names to hold ("Eelco")
I The length of an array: $#strings, returns the number ofitems in the array minus one. If equal to -1, the array doesnot exist or is empty.
print $#strings; → prints 2
I Assignment to $#strings changes the size of the array.$#strings = 0;→ @strings now holds ( "one" )
10/ 33
Hash variables (1)
I Start with the percentage (‘%’) sign.
I Made up of keys and values.
I Each key has exactly one corresponding value.
I Definition using parenthesized, comma delimited lists of keysand values:
%numbers = ( "one" => "one", "two" => 2 );
I Processing a single hash as a scalar using ‘{’ and ‘}’:print $numbers{"two"}; → prints "2"$numbers{"one"} = "1"; → we changed %numbers
11/ 33
Hash variables (2)
I Like arrays, hashes can be created using scalar assignment:$strings{"1"} = "one";→ creates %strings to hold ( "1" => "one" )
I The keys <hash> function will return an array filled with allthe keys in the hash.
print keys %numbers; → prints ( "one", "two" )
Question: How do ascertain the number of items in ahash?
12/ 33
Flow control
I A block of code contain a list of statements.
I Code blocks are delimited by ‘{’ and ‘}’
I A perl program is also a block of code.
I Flow control can be excerted using looping or conditionalstatements.
13/ 33
Looping Statements
I For loops are for repetition
I Using a list and an index variable a block of code will beexecuted for each value in the list.
for $i ( 1, 2, 3, 4 ) { . . . }
I Using ‘..’ you can also give a range:for $i ( 1 .. 3, 4 ) { . . . }
I The list can contain any scalars or other lists.@range = ( 1 .. 3 );for $i ( @range, 4 ) { . . . }
14/ 33
Conditional Statements (1)
I Conditional statements:if ( test ) { . . . } elsif { . . . } else { . . . }unless ( test ) { . . . } else { . . . }while ( test ) { . . . }until ( test ) { . . . }
I The usual comparison operators for testing:<, >, ==, !=, <=, >=
I But comparison of strings using ‘eq’.0xa == " 10 " → true0xa eq " 10 " → false
15/ 33
Conditional Statements (2)
if ($a == 5) {print "It’s five!\n";
} elsif ($a == 6) {print "It’s six!\n";
} else {print "It’s something else.\n";
}
unless ($pie eq ’apple’) {print "Ew, I don’t like $pie flavored pie.\n";
} else {print "Apple! My favorite!\n";
}
16/ 33
Conditional Statements (3)
$a = 0;
while ($a != 3) {$a++;print "Counting up to $a...\n";
}
until ($a == 0) {$a--;print "Counting down to $a...\n";
}
17/ 33
Perl Regular expressions (1)
I Very mature, can be highly complex
I Can be used for matching (testing) or transliteration.
I Simple syntax is / . . . /
I The matching operator ‘=~’ is used for testing
Perl: if ("This is perl!" =~ /is/) {print "Match!";
}output: Match!
18/ 33
Perl Regular expressions (2)
Jaap already treated most of this:
I ‘^’ and ‘$’ match the beginning and end of a stringrespectively.
I You can use character classes (‘[’ . . . ‘]’).
I You can quantify matches using ‘*’, ‘+’ or ‘?’ after a characteror character class.
I You can quantify matches generically using ‘{ from , to }’.
I ‘.’ matches any character.
I Use a backslash (‘\’) to escape characters like:‘.’, ‘^’, ‘$’, ‘/’, ‘\’, ‘{’, ‘}’, ‘[’, ‘]’, . . . .
19/ 33
Perl Regular expressions (3)
Metacharacters in regular expressions:
\d Matches a single digit character\w Matches a single word character (a letter, digit or underscore)\s Matches a whitespace character. . . . . .
Flags that can follow a regular expression:
i Match case insensitivelyg Remember the current position for the next matching
20/ 33
Perl Regular expressions (4)
Matching subexpressions:
I You can match subexpressions by encapsulating themwith ‘(’ and ‘)’
I Each subexpression is stored in a variable $1 . . . $n, which canbe used later on.
Perl: "This is it!" =~ /\s(..)/;print $1;
Question: What is printed by the above lines?
21/ 33
Perl Regular expressions (4)
Search and replace:
I Using s/ regexp / replacement /
Perl: $a = "This is it, or is it?"$a =~ s/\s.(s)/ wa$1/;print $a;
output: This was it, or is it?
I Using the g flag the replacement will be made for all matches,instead of just the first one.
Perl: $a = "This is it, or is it?"$a =~ s/\s.(s)/ wa$1/g;print $a;
output: This was it, or was it?
22/ 33
Subroutines
I Subs are functions, they can have any arguments
I The arguments are handed down using the special array @_
I A value can be returned using return
Perl: sub multiply {my (@ops) = @_;return $ops[0] * $ops[1];
}multiply(2, 3);
output: 6
23/ 33
Packages (1)
I Packages are a way to split up perl code into several pieces
I A package can be included into a piece of code by using use
I Each package represents a new namespace
I Create a package by creating a new file, generally ending in.pm
I The code for the class you are creating goes in there.
I The classname often is the same as the filename, this is easierto use, but not obligatory.
24/ 33
Packages (2)
Create a new file, for instance MyPackage.pm
I The first line should provide the name of the class in thepackage:
package MyPackage;
I Next comes the code for the package . . .
I The file should end with 1; to indicate to the loading modulethat the entire package was read successfully.
Example:
package MyPackage;print "WOW, it worked!\n";1;
25/ 33
Packages (3)
To use our package run the following perl code:
#!/usr/bin/perluse MyPackage;
The output of the program:
WOW, it worked!
26/ 33
Packages (4)
I You can refer to variables and filehandles in other packages byprefixing the identifier with the package name and a doublecolon:
$Package::Variable
I You can create subs in a package in the normal way
I They can be called from the program using the package:$Package::the_sub("well?")
I Special code blocks can be used for initialization anddestruction:
BEGIN {}, END {}, INIT {}, CHECK {}
Use perldoc perlmod to get more information
27/ 33
Objects (1)
“An Object is simply a reference that happens to knowwhich class it belongs to.”
I No special syntax for constructors, you have to make your own
I An object is created using the bless()
I The bless() function creates a reference to an object
I Anything can become blessed
I bless {} allocates an anonymous, empty hash and returns areference to it
28/ 33
Objects (2)
Using an anonymous reference:
package Critter;sub new { bless {} }
Using anonymous objects the class will not know itself, using aknown reference:
package Critter;sub new {my $self = {};bless $self;return $self;
}
29/ 33
Classes (1)
“A class is simply a package that happens to providemethods to deal with object references.”
I A class provides the methods for dealing with its reference
I Construction by defining a constructor function, generallynew()
package Critter;sub new {my $self = {};bless $self;return $self;
}
30/ 33
Classes (2)
I A method is simply a subroutine that expects an objectreference (or a package name, for class methods) as the firstargument.
I A constructor can call methods using the reference
sub new {my $self = {};bless $self;$self->initialize();return $self;
}
31/ 33
Classes (3)
I Classes can be inherited
I Use the two argument version of bless()
I Bless an object into a class
sub new {my $class = shift;my $self = {};bless $self, $class;$self->initialize();return $self;
}
32/ 33
Documentation
I BOOKS!, they are in the back of the classroom. . .
I Use the web, there are a lot of websites on perl
I Check www.perl.com for help.
I Find out about perldoc
Material for these slides was taken fromhttp://www.perl.com/pub/a/2000/10/begperl1.html
33/ 33