1 / 29

Perl

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

micheal
Download Presentation

Perl

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Colin Brown COMP 205 Perl Note: Several slides taken/adapted from slides for COMP 461, Spring 2004, by the author.

  2. 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

  3. Note All double quotes in these slides should be ", not “ and ”, which may have been accidentally inserted by PowerPoint or OOO Impress

  4. 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

  5. Checking and Running Your Script • To “compile” your script to check out its syntax: perl –c filename • To run your script: perl filename [ arguments ]

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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

  12. 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

  13. 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) ...

  14. 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"; }

  15. 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

  16. $ 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"; }

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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 };

  24. “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]

  25. 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";

  26. 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"; }

  27. 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} ";

  28. 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

  29. 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

More Related