Why Perl? n Perl is built around regular expressions ¨ REs are good for string processing ¨ Therefore Perl is a good scripting language ¨ Perl is especially popular for CGI scripts n n Perl makes full use of the power of UNIX Short Perl programs can be very short ¨ “Perl is designed to make the easy jobs easy, without making the difficult jobs impossible. ” -Larry Wall, Programming Perl HY 439 Autumn 2005 2
Why not Perl? n Perl is very UNIX-oriented ¨ Perl is available on other platforms. . . ¨. . . but isn’t always fully implemented there ¨ However, Perl is often the best way to get some UNIX capabilities on less capable platforms n Perl does not scale well to large programs ¨ Weak n subroutines, heavy use of global variables Perl’s syntax is not particularly appealing HY 439 Autumn 2005 3
What is a scripting language? n Operating systems can do many things ¨ copy, move, create, delete, compare files ¨ execute programs, including compilers ¨ schedule activities, monitor processes, etc. n n A command-line interface gives you access to these functions, but only one at a time A scripting language is a “wrapper” language that integrates OS functions HY 439 Autumn 2005 4
Major scripting languages n n n UNIX has sh, Perl Macintosh has Apple. Script, Frontier Windows has no major scripting languages ¨ probably n due to the weaknesses of DOS Generic scripting languages include: ¨ Perl (most popular) ¨ Tcl (easiest for beginners) ¨ Python (new, Java-like, best for large programs) HY 439 Autumn 2005 5
Perl Example 1 #!/usr/local/bin/perl # # Program to do the obvious # print 'Hello world. '; # Print a message HY 439 Autumn 2005 6
Comments on “Hello, World” n Comments are # to end of line the first line, #!/usr/local/bin/perl, tells where to find the Perl compiler on your system ¨ But n n n Perl statements end with semicolons Perl is case-sensitive Perl is compiled and run in a single operation HY 439 Autumn 2005 7
Perl Example 2 #!/ex 2/usr/bin/perl # Remove blank lines from a file # Usage: singlespace < oldfile > newfile while ($line = <STDIN>) { if ($line eq "n") { next; } print "$line"; } HY 439 Autumn 2005 8
More Perl notes n On the UNIX command line; < filename means to get input from this file ¨ > filename means to send output to this file ¨ n n In Perl, <STDIN> is the input file, <STDOUT> is the output file Scalar variables start with $ Scalar variables hold strings or numbers, and they are interchangeable Examples: $priority = 9; ¨ $priority = '9'; ¨ n Array variables start with @ HY 439 Autumn 2005 9
Perl Example 3 #!/usr/local/bin/perl # Usage: fixm <filenames> # Replace r with n -- replaces input files foreach $file (@ARGV) { print "Processing $filen"; 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 '