Top Banner
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin
42

CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

Jan 18, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

CPTG286K Programming - Perl

Chapter 1: A Stroll Through Perl

Instructor: Denny Lin

Page 2: 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

Page 3: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 4: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 5: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 6: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 7: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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 }

Page 8: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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 }

Page 9: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 10: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

Accessing PERL arrays

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

Page 11: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 12: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

);

Page 13: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 14: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

Lecture 2 Outline

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

• What Is Truth?

• Subroutines

• Filehandles

Page 15: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 16: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 17: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 18: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 19: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 20: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 21: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 22: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

Subroutines

• Defined using sub subroutine_name { }

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

• Subroutines return values using the return statement

Page 23: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

}

Page 24: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 25: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

}

Page 26: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 27: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 28: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

}

Page 29: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 30: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

Example sending e-mail warning

sub good_word

{

my($somename, $someguess) = @_; #name of parameters

[…rest of program deleted…]

else

{ # mail [email protected]

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

}

}

Page 31: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 32: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

}

Page 33: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 34: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

Format definition example

format STDOUT =

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

$filename, $name, $word

.

format STDOUT_TOP =

Page @<<

$%

Filename Name Word

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

.

Page 35: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 36: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 37: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 38: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 39: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 40: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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

Page 41: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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.

Page 42: CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

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.