290 likes | 417 Views
Colin Brown COMP 205. Perl. Note: Several slides taken/adapted from slides for COMP 461, Spring 2004, by the author. Perl. “Practical Extraction and Report Language” AKA: “Pathologically Eclectic Rubbish Lister” (and others) Invented by Larry Wall
E N D
Colin Brown COMP 205 Perl Note: Several slides taken/adapted from slides for COMP 461, Spring 2004, by the author.
Perl • “Practical Extraction and Report Language” • AKA: “Pathologically Eclectic Rubbish Lister” (and others) • Invented by Larry Wall • Wall’s goal: “Easy things should be easy and hard things should be possible.” • Eclectic blend of features from several languages • Often used as an active Web-server scripting language • Responds to an HTTP request by generating the HTML for the response page • Typically also saves user data and/or retrieves data for the response. • Also popular for building system administration tools • Influence on recent languages such as Ruby
Note All double quotes in these slides should be ", not “ and ”, which may have been accidentally inserted by PowerPoint or OOO Impress
The Role of Perl in Server-Side Response Handling and Page Generation An Aside Browser Server POST or GET HTTP (Web) Server Form Response Page ValidationResult ValidationRequest URL HTTP Parameters Response Page (HTML) JavaScript Code Perl
Checking and Running Your Script • To “compile” your script to check out its syntax: perl –c filename • To run your script: perl filename [ arguments ]
Documentation • http://www.perl.com/doc/manual/html/pod/ • Commonly used: • perldata: data types • perlfunc: built in functions • permod: how modules work • permodinstall: how to install modules • perlop: operators • perlsub: subroutines • perlsyn: general syntax • perlvar: predefined variables Perl Online Documentation
Hello World print "Hello world!\n"; # This is a comment. # This entire line is a comment. Source: http://www.perl.com/pub/a/2000/10/begperl1.html
Perl Variables • $abc – a scalar variable called “abc” • @def – an array variable called “def” • %ghi – a hashtable variable called “ghi” scalar: having a single value
Perl Scalars $i = 5; $pie_flavor = 'apple'; $constitution1776 = "We the People, "; "References" and "file handles" are also scalars Source: http://www.perl.com/pub/a/2000/10/begperl1.html
Arrays @months = ("July", "August", "September"); print $months[0]; # This prints "July". $months[2] = "Smarch"; #We just renamed Sept Array members must be scalars. Note Arrays of more complex stuff must use references. Source: http://www.perl.com/pub/a/2000/10/begperl1.html
Hashs %days_in_month = ( "July" => 31, "August" => 31, "September" => 30 ); print $days_in_month{"September"}; # 30 $days_in_month{"February"} = 29; # leap year. Note Source: http://www.perl.com/pub/a/2000/10/begperl1.html
Statement Delineation print "This is "; print "two statements.\n"; print "But this ", "is only one statement.\n"; Also note: two arguments to the print function. Source: http://www.perl.com/pub/a/2000/10/begperl1.html
For Loops for $i (1,2,3,4,5) { print $i, "\n"; } $ perl for.pl 1 2 3 4 5 Often want $i to be a local variable: for my $i (1,2,3,4,5) ...
Other Forms of for $ perl for.pl a: 1 a: 2 a: 3 b: 1 b: 2 b: 3 c: 1 c: 2 c: 3 d: 1 d: 2 d: 3 for $i (1,2,3) { print "a: $i\n"; } for ($i = 0; $i < 3; $i++ ) { print "b: ", $i+1, "\n"; } for $i ( 1 ... 3) { print "c: $i\n"; } @a = ( 1... 3); for $i (@a) { print "d: $i\n"; }
Sorting • See Sort in perlfunc* • Syntax forms: • sort SUBNAME LIST • sort BLOCK LIST • sort LIST • See <=> and cmp operators. • When comparison subroutine or block is run, $a and $b are set to values to be compared. numeric stringwise * http://www.perl.com/doc/manual/html/pod/perlfunc.html
$ perl sort.pl -1 1 205 3 42 1000 205 Dog cat dog 1000 205 cat Dog dog 1000 205 cat Dog dog Sorting @nums = ( 3, 42, 205, 1, -1); @strs = ( "Dog","cat","dog", "205", "1000"); for $i (sort @nums ) { print "$i\n"; } print "\n"; for $i (sort @strs ) { print "$i\n"; } print "\n"; sub ci { uc($a) cmp uc($b) } for $i ( sort ci @strs ) { print "$i\n"; } print "\n"; for $i ( sort {uc($a) cmp uc($b)} @strs ) { print "$i\n"; }
Parentheses and Function Calls print 1+2+4; # Prints 7. print(1+2) + 4; # Prints 3. print (1+2)+4; # Also prints 3! print +(1+2)+4; # Prints 7. print ((1+2)+4); # Prints 7. "It LOOKS like a function, therefore it IS a function, and precedence doesn't matter." Source: http://www.perl.com/doc/manual/html/pod/perlfunc.html
Here Documents $ perl here.pl The price is 2.3. The price is $Price. hi there lo there I said foo. I said bar. $Price = 2.30; print <<EOF; The price is $Price. EOF print <<'EOF'; The price is $Price. EOF #backquotes: print <<`EOC`; echo hi there echo lo there EOC print <<"foo", <<"bar"; I said foo. foo I said bar. bar Source: http://www.perl.com/doc/manual/html/pod/perldata.html
Here Documents – Not Just for Print Here's a line or two. 23 and here's another. sub myfunc { for my $i (@_) { print "$i\n"; } } myfunc(<<"THIS", 23, <<'THAT'); Here's a line or two. THIS and here's another. THAT What's @_? It's an array containing the arguments to the subprogram. Source: http://www.perl.com/doc/manual/html/pod/perldata.html
Modules • http://www.perl.com/CPAN/modules/index.html • If you're writing a module: the “package” statement • package Abc::Def #file is Abc/Def.pm • If you're using a package: the “use” or “require” statement use Abc::Def; #loads the module require Abc::Def; #makes it accessible #through references like Abc::Def::myFunc
Objects in Perl use XML::XPath; use XML::XPath::XMLParser; my $xpath = XML::XPath->new(filename => 'accounts.xml'); #find all <acct> tags inside <account> my $nodes = $xpath->find('/accounts/acct'); for my $n ($nodes->get_nodelist) { print "Acct:", $n->getAttribute("name"), "\n"; } For doc on Xpath module: http://search.cpan.org/~msergeant/XML-XPath-1.13/XPath.pm
Perl Data Structures • Relatively gentle introduction: perlreftut • Lots of cookbook examples: perldsc • All the details: perlref • Arrays and hashes always contain scalars • Array of hashes: really array of references to hashes • Hash of arrays: really hash of references to arrays
Making a Reference References are scalars. • @a = (1,2,3); • $aref1 = \@a; • $aref2 = [ @a ]; #copies the array • $aref3 = [1,3,4]; #anonymous array • %h = ( a=>1, b=>3, c=>9); • $href1 = \%h; • $href2 = { %h };
“Use Rules” for References • Use Rule 1: Use {$aref} where ever array/hash name can be used. • Example: if $aref = \@a then may use ${$aref}[0] instead of $a[0] • Use Rule 2 • ${$aref}[3] can be abbreviated $aref->[3] • Arrow Rule (multi-dimensional array/hash) • $a[1]->[2] can be abbreviated $a[1][2] • May omit {...} when they contain an atomic scalar • @{$aref} can be abbreviated @$aref • ${$aref}[1] can be abbreviated $$aref[1]
Some Examples from perldsc @AoA = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], ); push @AoA, [ split ]; @tmp = somefunc($i); $AoA[$i] = [ @tmp ]; print "elt $i $j is $AoA[$i][$j]\n";
Some Examples from perldsc %HoA = ( flintstones => [ "fred", "barney" ], jetsons => [ "george", "jane", "elroy" ], simpsons => [ "homer", "marge", "bart" ], ); $HoA{$who} = [ @fields ]; push @{ $HoA{"flintstones"} }, "wilma", "betty"; foreach $family ( keys %HoA ) { print "family: "; foreach $i ( 0 .. $#{ $HoA{$family} } ) { print " $i = $HoA{$family}[$i]"; } print "\n"; }
Some Examples from perldsc @AoH = ({ Lead => "fred", Friend => "barney", },{ Lead => "george", Wife => "jane", Son => "elroy", },{ Lead => "homer", Wife => "marge", Son => "bart", } ); $rec = {}; $rec->{$key} = $value; $AoH[0]{pet} = "dino"; $AoH[0]{lead} = "fred"; print "$role=$AoH[$i]{$role} ";
Perl Assignment • Choice of presentation • Generate HTML code • Generate formatted text • Pop up a window using a portable GUI toolkit (e.g., TK) • Choice of data representation • One of the complex data structures • Initialized in code • Read from a file • Parse your XML file from the XSLT assignment • NOT: data hard-coded in print statements
Use Rules for References • Use Rule 1: {$aref} can be used anywhere that the thing pointed to by $aref can be used. • If: $aref = \@a; • Then: ${$aref}[3] is same as $a[3] • Use Rule 2: ${$aref}[3] can be written $aref->[3] • Arrow Rule: $a[1]->[2] can be written $a[1][2] • May omit {...} if content is ref scalar: • @{$aref} can be written @$aref