cptg286k programming perl
Download
Skip this Video
Download Presentation
CPTG286K Programming - Perl

Loading in 2 Seconds...

play fullscreen
1 / 42

CPTG286K Programming - Perl - PowerPoint PPT Presentation


  • 401 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'CPTG286K Programming - Perl' - victoria


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
cptg286k programming perl

CPTG286K Programming - Perl

Chapter 1: A Stroll Through Perl

Instructor: Denny Lin

course objectives
Course Objectives
  • Learn to program in Perl
  • Use effective documentation techniques
  • Use clear programming style
lecture 1 outline
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
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
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
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

if then else string comparison
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
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
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
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
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;

}

storing tables in a hash
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
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
Lecture 2 Outline
  • String operations
    • Pattern match operator
    • Substitution operator
    • Translation operator
  • What Is Truth?
  • Subroutines
  • Filehandles
string operations
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
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
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
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 d19
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
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
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
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
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
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
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
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
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 example
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

}

sending e mail warnings
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
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

}

}

reading the next file
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 files
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: $!”;

}

}

formatting output
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 definition example

format STDOUT =

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

$filename, $name, $word

.

format STDOUT_TOP =

Page @<<

$%

Filename Name Word

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

.

sample output
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
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
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
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
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
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
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

.

sample output42
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.

ad