1 / 42

CPTG286K Programming - Perl

CPTG286K Programming - Perl. Chapter 1: A Stroll Through Perl Instructor: Denny Lin. Course Objectives. Learn to program in Perl Use effective documentation techniques Use clear programming style. Lecture 1 Outline. Hello world program Storing keyboard input into a scalar variable

victoria
Télécharger la présentation

CPTG286K Programming - 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. CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin

  2. Course Objectives • Learn to program in Perl • Use effective documentation techniques • Use clear programming style

  3. Lecture 1 Outline • Hello world program • Storing keyboard input into a scalar variable • If-then-else string comparison • Storing and accessing arrays • Else if blocks • Storing and accessing hashes

  4. Important UNIX commands • Use the pico editor to create PERL scripts: $ pico ex1.pl • Make sure PERL scripts have execute permissions $ chmod +x ex1.pl • Run PERL scripts by typing its full name $ ex1.pl

  5. Hello, world! # This is the standard Hello, world! program # Call the PERL compiler using -w (warning) switch #!/usr/bin/perl -w print (“Hello, world!\n”);

  6. Storing input from the keyboard • Get keyboard input with the <STDIN> construct • Store input in a scalar variable called $name Ex1.pl: #!/usr/bin/perl -w print “What is your name?”; # produce prompt $name = <STDIN>; # read keyboard chomp ($name); # rid trailing newline print “Hello, $name!\n”; # print output

  7. If-then-else string comparison • Statement blocks appear within curly brackets { } • Use the eq operator to compare equality of two strings, and ne to determine inequality • Use clear indentation style • DO NOT put curly brackets in comment: if ($name eq “Randal”) { # this end of block is never read }

  8. If-then-else comparison example Ex2.pl: #!/usr/bin/perl -w print “What is your name?”; # produce prompt $name = <STDIN>; # read keyboard chomp ($name); # rid trailing newline if ($name eq “Randal”) { print “Hello, Randal! How good of you to be here!\n”; } else { print “Hello, $name!\n”; } # ordinary greeting NOTE. The following DOES NOT work (why?): { print “Hello, $name!\n”; # ordinary greeting }

  9. Arrays in PERL • Each element of an array stores scalar variables • Array variable names start with an @ during assignment. For example: @words = (“camel”, “llama”, “alpaca”); • Use the qw() operator to quote words in an array. For example: @words = qw(camel llama alpaca);

  10. Accessing PERL arrays • Elements of an array are accessed as scalar variables: • $words[0] is camel • setting $i to 2, $words[$i] is alpaca

  11. If-then-elsif-else block • Note that an else if block is spelled elsif: if ($words[$i] eq $guess) # is guess correct? { $correct = “yes”; # guess is correct } elsif ($i < 2) # more words to look at? { $i = $i + 1; # increment $i } else { print “Wrong, try again. What is the secret word?”; $guess = <STDIN>; # read keyboard chomp ($guess); # rid trailing newline $i = 0; }

  12. Storing tables in a Hash • Hashes hold scalar values referenced by a key • Hash variables start with a % during assignment. For example: %words = qw( fred camel barney llama betty alpaca wilma alpaca );

  13. Accessing table data in a Hash • Hash data elements are accessed as scalar variables, and addressed with curly brackets: • $words{“betty”} is alpaca • setting $person to betty, $words{$person} is alpaca

  14. Lecture 2 Outline • String operations • Pattern match operator • Substitution operator • Translation operator • What Is Truth? • Subroutines • Filehandles

  15. String Operations • Pattern match operator • Use the =~ operator to match strings • Use slashes to make sure white/spaces are significant • Use ^ to specify a “start with” pattern • Use \b to denote word boundary • Use /i to ignore case

  16. Pattern Matching Example Ex3.pl #!/usr/bin/perl #Turn off warning: notice no –w switch […rest of program deleted …] chomp ($name); # rid trailing newline If ($name =~ /^randal\b/i) # Match names starting # with randal, use word # boundary, and ignore case { print “Hello, Randal! How good of you to be here!\n”; } […rest of program deleted …]

  17. String Operations (cont’d) • Substitution operator • Use the s operator to perform substitutions delimited by slashes • Regular expressions specify from and to what the operator will substitute. From and to entries are separated by a slash

  18. Substitution example • To substitute a string with another that doesn’t contain non-word characters • \W specifies all non-word characters • .* specifies characters to the end of string • A blank “to” entry substitutes all “from” entries • The following finds the first non-word character in $name, and substitutes them with blanks to the end of string $name =~ s/\W.*//;

  19. String Operations (cont’d) • Translation operator • Use the tr operator to perform translations delimited by slashes • Regular expressions specify from and to what the operator will translate. From and to entries are separated by a slash

  20. Translation example • To translate a list of uppercase characters into lowercase: • Specify the A-Z list in the “from” entry • Specify the a-z list in the “to” entry • The following turns any uppercase characters in $name into lowercase characters $name =~ tr/A-Z/a-z/;

  21. What Is Truth? • In PERL: • Any string is true except for “” and “0” • Any number is true except 0 • Any reference is true • Any undefined value is false From “Programming Perl” 3rd Edition Page 29-30

  22. Subroutines • Defined using sub subroutine_name { } • The my() operator defines private parameters stored in the @_ local array • Subroutines return values using the return statement

  23. Subroutine example sub good_word { my($somename, $someguess) = @_; # name of parameters $somename =~ s/\W.*//; # remove everything # after first word $somename =~ tr/A-Z/a-z/; # lowercase everything if ($someone eq “randal”) { return 1; } # return true elsif (($words{$someone} || “groucho”) eq $someguess { return 1; } # return true else { return 0; } # return false }

  24. Filehandles • Create user-defined filehandles to access files • Use the open() function to assign a filehandle to a file • Access file contents by assigning the scalar variable a filehandle value • Close the file with the close() operator

  25. Filehandle example sub init_words { open(WORDSLIST, “wordslist”); while ($name = <WORDSLIST>) # read name { chomp ($name); # rid trailing newline $word = <WORDSLIST>; # read word chomp ($word); # rid trailing newline $words{$name} = $word; # Put into hash table } close (WORDSLIST); # close file }

  26. Lecture 3 Outline • Checking age of files • Sending e-mail warnings • Reading the next file • Formatting output • Renaming files • Saving hash tables into a database • Retrieving information from a database

  27. Checking the age of files • Assign a filehandle to a file for examination • Use the –M file test operator to check the age of the file • Compare the filehandle to the number of days

  28. File age checking example sub init_words { open (WORDSLIST, “wordslist”) || # open file or die “Can’t open wordlist: $!”; # exit & print error if (-M WORDSLIST >= 7.0) # is age of file >= 7 days? { # print error and exit die “Sorry, the wordslist is older than seven days.”; } while ($name = <WORDSLIST>) # read name { chomp ($name); # rid trailing newline $word = <WORDSLIST>; # read word chomp ($word); # rid trailing newline $words{$name} = $word; # put into hash table } close (WORDSLIST) || # close file or die “Couldn’t close wordlist: $!”; # print error and exit }

  29. Sending e-mail warnings • Use the open() function to create a filehandle to the MAIL process • Pipe your e-mail address into the MAIL process • Write message into the MAIL process • Close filehandle to the MAIL process

  30. Example sending e-mail warning sub good_word { my($somename, $someguess) = @_; #name of parameters […rest of program deleted…] else { # mail joedoe@lasierra.edu open MAIL, “|mail joedoe\@lasierra.edu”; # write text of e-mail print MAIL “Warning: $someone guessed $someguess\n”; close MAIL; # close MAIL filehandle return 0; # return value is false } }

  31. Reading the next file • The glob function returns the next filename that matches a search pattern • Put the glob function in a while loop to list all files in a directory

  32. Example of reading next files sub init_words { while ( defined ($filename = glob(“*.secret”)) ) { # find next file until undef open (WORDSLIST, $filename) || # open file or die “Can’t open wordlist: $!”; # print error, exit if (-M WORDSLIST < 7.0) # complement test { while ($name = <WORDSLIST>) { # read until undef chomp $name; # rid trailing newline $word = <WORDSLIST>; # get word chomp $word; # rid trailing newline $words{name} = $word; # put into table } } close (WORDSLIST) || die “Couldn’t close wordlist: $!”; } }

  33. Formatting output • The format statement is used to layout reports by formatting output variables • A single write; command is used execute a report • Formats definitions contain a format name, and a template definition • Template definitions contain fieldlines and fieldholders

  34. Format definition example format STDOUT = @<<<<<<<<<<<<<< @<<<<<<<< @<<<<<<<<<<<< $filename, $name, $word . format STDOUT_TOP = Page @<< $% Filename Name Word =============== ========= ============= .

  35. Sample Output Page 1 Filename Name Word =============== ========= ============= barney.secret christina rabbit barney.secret joey fish barney.secret jennifer jellyfish fred.secret fred camel fred.secret barney llama fred.secret betty alpaca fred.secret wilma alpaca

  36. Renaming files • Use the rename function to alter the name of files • When used in conjunction with a check for the age of next files, older files can be automatically renamed

  37. Example renaming expired files sub init_words { while ( defined($filename = glob("*.secret")) ) { open(WORDSLIST, $filename) || die "Can't open wordlist: $!"; if (-M WORDSLIST < 7.0) { […rest of program deleted…] } else { rename ($filename,"$filename.old") || die "can't rename $filename to $filename.old: $!"; } close (WORDSLIST) || die "Couldn't close wordlist: $!"; } }

  38. Saving hash tables in a database • The dbmopen() statement can create a hash table that stores information on a database file • Information is stored into the hash table by assigning values for a key • The dbmclose() statement disconnects the hash from the database file

  39. Saving hash table data example […the following goes at the end of the main section of Ex3.pl…] # log all successful accesses # last_good hash contains successful accesses dbmopen (%last_good,”lastdb”,0666); $last_good{$name} = time; dbmclose(%last_good);

  40. Retrieving info from database • Use the dbmopen() statement to get hash table data from database file • Use a foreach loop to process each entry (key) from the database file. • Use the sort and keys functions to produce a sorted list • Store and calculate result from hash into scalar variable • Execute report using a write; statement

  41. Example retrieving database info Ex4.pl #!/usr/bin/perl dbmopen (%last_good,"lastdb",0666); # open lastdb using # 0666 file permission foreach $name (sort keys %last_good) # process each entry { $when = $last_good{$name}; # assign hash data to # scalar variable which # contains data in seconds $hours = (time - $when) / 3600; # compute hours ago write; # execute report } format STDOUT = User @<<<<<<<<<<<<<: last correct guess was @<<< hours ago. $name, $hours .

  42. Sample Output User Betty : last correct guess was 0.01 hours ago. User Denny : last correct guess was 0.09 hours ago. User Fred : last correct guess was 0.09 hours ago. User barney : last correct guess was 0.01 hours ago. User christina : last correct guess was 0.00 hours ago. User jennifer : last correct guess was 0.00 hours ago. User joey : last correct guess was 0.00 hours ago. User wilma : last correct guess was 0.00 hours ago.

More Related