cptg286k programming - perl chapter 1: a stroll through perl instructor: denny lin

Post on 18-Jan-2016

219 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

• If-then-else string comparison

• Storing and accessing arrays

• Else if blocks

• Storing and accessing hashes

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

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”);

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 -wprint “What is your name?”; # produce prompt$name = <STDIN>; # read keyboardchomp ($name); # rid trailing newlineprint “Hello, $name!\n”; # print output

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 }

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 }

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);

Accessing PERL arrays

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

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 keyboardchomp ($guess); # rid trailing newline$i = 0;}

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

);

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

Lecture 2 Outline

• String operations– Pattern match operator– Substitution operator– Translation operator

• What Is Truth?

• Subroutines

• Filehandles

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

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 …]

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

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.*//;

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

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/;

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

Subroutines

• Defined using sub subroutine_name { }

• The my() operator defines private parameters stored in the @_ local array

• Subroutines return values using the return statement

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

}

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

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

}

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

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

File age checking examplesub init_words{

open (WORDSLIST, “wordslist”) || # open file ordie “Can’t open wordlist: $!”; # exit & print error

if (-M WORDSLIST >= 7.0) # is age of file >= 7 days?{ # print error and exitdie “Sorry, the wordslist is older than seven days.”;}

while ($name = <WORDSLIST>) # read name{chomp ($name); # rid trailing newline$word = <WORDSLIST>; # read wordchomp ($word); # rid trailing newline$words{$name} = $word; # put into hash table}

close (WORDSLIST) || # close file ordie “Couldn’t close wordlist: $!”; # print error and exit

}

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

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

}

}

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

Example of reading next filessub init_words{

while ( defined ($filename = glob(“*.secret”)) ){ # find next file until undefopen (WORDSLIST, $filename) || # open file or

die “Can’t open wordlist: $!”; # print error, exitif (-M WORDSLIST < 7.0) # complement test

{while ($name = <WORDSLIST>)

{ # read until undefchomp $name; # rid trailing newline$word = <WORDSLIST>; # get wordchomp $word; # rid trailing newline$words{name} = $word; # put into table}

}close (WORDSLIST) || die “Couldn’t close wordlist: $!”;}

}

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

Format definition example

format STDOUT =

@<<<<<<<<<<<<<< @<<<<<<<< @<<<<<<<<<<<<

$filename, $name, $word

.

format STDOUT_TOP =

Page @<<

$%

Filename Name Word

=============== ========= =============

.

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

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

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: $!"; }}

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

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);

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

Example retrieving database info

Ex4.pl#!/usr/bin/perldbmopen (%last_good,"lastdb",0666); # open lastdb using

# 0666 file permissionforeach $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.

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.

top related