Introduction to Perl Part III By Bridget Thomson

Introduction to Perl Part III By: Bridget Thomson Mc. Innes 6 Feburary 2004

Hashes n n n Hashes are like array, they store collections of scalars. . . but unlike arrays, indexing is by name Two components to each hash entry: – Key – Value n example : name example : phone number Hashes denoted with % – Example : %phone. Directory n Elements are accessed using {} (like [] in arrays)

Hashes continued. . . n Adding a new key-value pair $phone. Directory{“Shirly”} = 7267975 – Note the $ to specify “scalar” context! n Each key can have only one value $phone. Directory{“Shirly”} = 7265797 # overwrites previous assignment Multiple keys can have the same value n Accessing the value of a key n $phone. Number =$phone. Directory{“Shirly”};

Hashes and Foreach n Foreach works in hashes as well! foreach $person (keys %phone. Directory) { print “$person: $phone. Directory{$person}”; } n Never depend on the order you put key/values in the hash! Perl has its own magic to make hashes amazingly fast!!

Hashes and Sorting The sort function works with hashes as well n Sorting on the keys n foreach $person (sort keys %phone. Directory) { print “$person : $directory{$person}n”; } – This will print the phone. Directory hash table in alphabetical order based on the name of the person, i. e. the key.

Hash and Sorting cont. . . n Sorting by value foreach $person (sort {$phone. Directory{$a} <=> $phone. Directory{$b}} keys %phone. Directory) { print “$person : $phone. Directory{$person}n”; } – Prints the person and their phone number in the order of their respective phone numbers, i. e. the value.

A Quick Program using Hashes n Count the number of Republicans in an array %seen = (); # initialize hash to empty @polit. Array = ( “R”, “D”, “I”, “D”, “R”, “G” ); foreach $politician (@polit. Array) { $seen{$politician}++; } print “Number of Republicans = $seen{'R'}n”;

Slightly more advanced program n Count the number of parties represented, and by how much! %seen = (); # initialize hash to empty @polit. Array = ( “R”, “D”, “I”, “D”, “R”, “G” ); foreach $politician (@polit. Array) { $seen{$politician}++; } foreach $party (keys %seen) { print “Party : $party. Num reps: $seen{$party}n”; }

Command Line Arguments Command line arguments in Perl are extremely easy. n @ARGV is the array that holds all arguments passed in from the command line. n – Example: § %. /prog. pl arg 1 arg 2 arg 3 – @ARGV would contain ('arg 1', arg 2', 'arg 3) n $#ARGV returns the number of command line arguments that have been passed. – Remember $#array is the size of the array!

Quick Program with @ARGV n Simple program called log. pl that takes in a number and prints the log base 2 of that number; #!/usr/local/bin/perl -w $log = log($ARGV[0]) / log(2); print “The log base 2 of $ARGV[0] is $log. n”; n Run the program as follows: – % log. pl 8 n This will return the following: – The log base 2 of 8 is 3.

Another Example Program n You want to print the binary form of an integer #!/usr/local/bin/perl -w foreach $integer (@ARGV) { # converts the integer to a 32 bit binary number @binary=split//, unpack(“B 32”, pack(“N”, $integer)); # Store the last 4 elements of @binary into @bits = @binary[28. . $#binary]; # Print the integer and its binary form print “$integer : @bitsn”; }

$_ Perl default scalar value that is used when a variable is not explicitly specified. n Can be used in n – For Loops – File Handling – Regular Expressions

$_ and For Loops n Example using $_ in a for loop @array = ( “Perl”, “C”, “Java” ); for(@array) { print $_. “is a language I known”; } – Output : Perl is a language I know. C is a language I know. Java is a language I know.

$_ and File Handlers n Example in using $_ when reading in a file; while( <> ) { chomp $_; # remove the newline char @array = split/ /, $_; # split the line on white space # and stores data in an array } n Note: – The line read in from the file is automatically store in the default scalar variable $_

$_ and File Handling cont. . Another example similar to the previous example: while(<>) { chomp; # chars @array = split/ /; # # # } n removes trailing newline splits the line on white space and stores the data in the array Notes: – The functions chomp and split automatically perform their respective operations on $_.

Example Program n Count the number of words in a text and display the top 10 most frequency words. #!/usr/local/bin/perl %vocab = (); $counter = 0; while(<>) { chomp; foreach $element (split/ /) { $vocab{$element}++; } } foreach $word (sort {$vocab{$b}<=>$vocab{$a}} %vocab) { print “$word $vocab{$word}n”; if($counter == 10) { last; } $counter++; }

$_ and Regular Expressions n Example in using $_ when using regular expressions while( <> ) { chomp; $_=~s/[. !, ; ]/ /; $_=~s/I am/Why are you/; print “$_? n”; } n Input line : – I am feeling down today. n Output : – Why are you feeling down today?

Perl Modules n What are Perl Modules? – Batches of reusable code – Allow for object oriented Perl Programming n Comprehensive Perl Archive Network (CPAN) – Perl utilities – Perl Modules – Perl documentation – Perl distribution

CPAN Organization CPAN Material is organized by – Modules – Distributions – Documentation – Announcements – Ports – Scripts – Authors n Distributions are ‘tar-gzipped’ – tar – gzip n

Categories of Modules by-author – Modules are organized by author’s registered CPAN name n by-category – Modules categorized by subject matter n by-module – Modules categorized by module name n

Installing a Module n After you have gunziped and untared your module you have two options on installing your module depending upon if you have root privileges to the location where perl modules are installed or you don’t. n If you have root privileges or write access: § perl Makefile. PL § make test § make install

Local Install n Need to specify where you would like the module to be installed by setting the PREFIX argument when generating a Makefile from Makfile. PL – – perl Makefile. PL PREFIX=/home/Perl/Modules make test make install

Local Install cont… Perl usually looks in system wide areas for modules, therefore it will not find your local module unless you tell Perl where to find it. n In your perl program where you will be using your module n #!/usr/local/bin/perl use lib ‘<module location>’ use Module. Name;

‘using’ a Perl Module n If we have a module called Test. Module that contains a function test_me(). To use this module we have two options: – Object Oriented use Test. Module; $test = Test. Module->new() $test->test_me() – Standard use Test. Module test_me();

Example Program #!/usr/local/bin/perl use lib ‘home/cs/bthomson/Perl. Modules/Suffix. pm’ use Suffix. pm $sarray->Array: : Suffix->new(); $sarray->create_files(“hamlet. txt”); $sarray->get_ngrams();

Module Documentation Perl Module Documentation is provided by the module author and usually written in pod format n To view the documentation on the command line – %perldoc modulename n Convert the pod document to the format of your choice: – pod 2 text converts to a text file – pod 2 html converts to an html file – pod 2 man converts to a man page file n

Thank you
- Slides: 27