PerlWhy Perl?Why not Perl?What is a scripting language?Major scripting languagesPerl Example 1Comments on “Hello, World”Perl Example 2More Perl notesPerl Example 3Comments on example 3Arithmetic in PerlString and assignment operatorsSingle and double quotesArrayspush and popforeachTestsfor loopswhile loopsdo..while and do..until loopsif statementsif - elsif statementsSlide 24Basic pattern matchingRE special charactersRE examplesSquare bracketsMore examplesMore special charactersQuoting special charactersAlternatives and parenthesesSubstitutionThe $_ variableGlobal substitutionsCase-insensitive substitutionsRemembering patternsDynamic matchingtrsplitAssociative arraysAssociative Arrays IIAssociative Arrays IIICalling subroutinesDefining subroutinesReturning a resultLocal variablesExample subroutinePerl 5The EndJan 13, 2019PerlMajor parts of this lecture adapted from http://www.scs.leeds.ac.uk/Perl/start.html2Why Perl?Perl is built around regular expressionsREs are good for string processingTherefore Perl is a good scripting languagePerl is especially popular for CGI scriptsPerl makes full use of the power of UNIXShort Perl programs can be very short“Perl is designed to make the easy jobs easy, without making the difficult jobs impossible.” -- Larry Wall, Programming Perl3Why not Perl?Perl is very UNIX-orientedPerl is available on other platforms......but isn’t always fully implemented thereHowever, Perl is often the best way to get some UNIX capabilities on less capable platformsPerl does not scale well to large programsWeak subroutines, heavy use of global variablesPerl’s syntax is not particularly appealing4What is a scripting language?Operating systems can do many thingscopy, move, create, delete, compare filesexecute programs, including compilersschedule activities, monitor processes, etc.A command-line interface gives you access to these functions, but only one at a timeA scripting language is a “wrapper” language that integrates OS functions5Major scripting languagesUNIX has sh, PerlMacintosh has AppleScript, FrontierWindows has no major scripting languagesprobably due to the weaknesses of DOSGeneric scripting languages include:Perl (most popular)Tcl (easiest for beginners)Python (new, Java-like, best for large programs)6Perl Example 1#!/usr/local/bin/perl## Program to do the obvious#print 'Hello world.'; # Print a message7Comments on “Hello, World”Comments are # to end of lineBut the first line, #!/usr/local/bin/perl, tells where to find the Perl compiler on your systemPerl statements end with semicolonsPerl is case-sensitivePerl is compiled and run in a single operation8Perl Example 2#!/ex2/usr/bin/perl# Remove blank lines from a file# Usage: singlespace < oldfile > newfilewhile ($line = <STDIN>) { if ($line eq "\n") { next; } print "$line";}9More Perl notesOn the UNIX command line;< filename means to get input from this file> filename means to send output to this fileIn Perl, <STDIN> is the input file, <STDOUT> is the output fileScalar variables start with $Scalar variables hold strings or numbers, and they are interchangeableExamples:$priority = 9;$priority = '9';Array variables start with @10Perl Example 3#!/usr/local/bin/perl# Usage: fixm <filenames># Replace \r with \n -- replaces input filesforeach $file (@ARGV) { print "Processing $file\n"; if (-e "fixm_temp") { die "*** File fixm_temp already exists!\n"; } if (! -e $file) { die "*** No such file: $file!\n"; } open DOIT, "| tr \'\\015' \'\\012' < $file > fixm_temp" or die "*** Can't: tr '\015' '\012' < $infile > $outfile\n"; close DOIT; open DOIT, "| mv -f fixm_temp $file"or die "*** Can't: mv -f fixm_temp $file\n"; close DOIT;}11Comments on example 3In # Usage: fixm <filenames>, the angle brackets just mean to supply a list of file names hereIn UNIX text editors, the \r (carriage return) character usually shows up as ^M (hence the name fixm_temp)The UNIX command tr '\015' '\012' replaces all \015 characters (\r) with \012 (\n) charactersThe format of the open and close commands is:open fileHandle , fileNameclose fileHa ndle , fileName "| tr \'\\015' \'\\012' < $file > fixm_temp" says: Take input from $file, pipe it to the tr command, put the output on fixm_temp12Arithmetic in Perl$a = 1 + 2; # Add 1 and 2 and store in $a$a = 3 - 4; # Subtract 4 from 3 and store in $a$a = 5 * 6; # Multiply 5 and 6$a = 7 / 8; # Divide 7 by 8 to give 0.875$a = 9 ** 10; # Nine to the power of 10, that is, 910$a = 5 % 2; # Remainder of 5 divided by 2++$a; # Increment $a and then return it$a++; # Return $a and then increment it--$a; # Decrement $a and then return it$a--; # Return $a and then decrement it13String and assignment operators$a = $b . $c; # Concatenate $b and $c$a = $b x $c; # $b repeated $c times$a = $b; # Assign $b to $a$a += $b; # Add $b to $a$a -= $b; # Subtract $b from $a$a .= $b; # Append $b onto $a14Single and double quotes$a = 'apples';$b = 'bananas';print $a . ' and ' . $b;prints: apples and bananasprint '$a and $b';prints: $a and $bprint "$a and $b";prints: apples and bananas15Arrays@food = ("apples", "bananas", "cherries");But… print $food[1];prints "bananas" @morefood = ("meat", @food);@morefood == ("meat", "apples", "bananas", "cherries");($a, $b, $c) = (5, 10, 20);16push and poppush adds one or more things to the end of a listpush (@food, "eggs", "bread");push returns the new length of the listpop removes and returns the last element$sandwich = pop(@food);$len = @food; # $len gets length of @food$#food # returns index of last element17foreach# Visit each item in turn and call it $morselforeach $morsel (@food){ print "$morsel\n"; print "Yum yum\n"; }18Tests“Zero” is false. This includes:0, '0', "0", '', ""Anything not false is trueUse == and != for numbers, eq and ne for strings&&, ||, and ! are and, or, and not, respectively.19for loopsfor loops are just as in C or Javafor ($i = 0; $i < 10; ++$i){ print "$i\n";}20while loops#!/usr/local/bin/perlprint "Password? ";$a = <STDIN>;chop $a; # Remove the last character (\n)while ($a ne "fred"){ print "sorry. Again? "; $a =
View Full Document