Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Introduction to Perl Part III By: Bridget Thomson McInnes 6 Feburary 2004."— Presentation transcript:

1 Introduction to Perl Part III By: Bridget Thomson McInnes 6 Feburary 2004

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

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

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

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

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

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

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

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

10 Quick Program with @ARGV 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”; Run the program as follows: – –% log.pl 8 This will return the following: – –The log base 2 of 8 is 3.

11 Another Example Program You want to print the binary form of an integer 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 # converts the integer to a 32 bit binary number @binary=split//,unpack(“B32”,pack(“N”,$integer)); @binary=split//,unpack(“B32”,pack(“N”,$integer)); # Store the last 4 elements of @binary into @bits # Store the last 4 elements of @binary into @bits @bits = @binary[28..$#binary]; @bits = @binary[28..$#binary]; # Print the integer and its binary form # Print the integer and its binary form print “$integer : @bits\n”; print “$integer : @bits\n”;}

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

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

14 $_ and File Handlers 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 } Note: – –The line read in from the file is automatically store in the default scalar variable $_

15 $_ and File Handling cont.. Another example similar to the previous example: while(<>) { chomp; # removes trailing newline chars @array = split/ /; # 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 $_.

16 Example Program Count the number of words in a text and display the top 10 most frequency words. 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”; print “$word $vocab{$word}\n”; if($counter == 10) { last; } $counter++; if($counter == 10) { last; } $counter++;}

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

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

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

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

21 Installing a Module 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. 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. If you have root privileges or write access: If you have root privileges or write access:  perl Makefile.PL  make  make test  make install

22 Local Install Need to specify where you would like the module to be installed by setting the PREFIX argument when generating a Makefile from Makfile.PL 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 –make test –make install

23 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. 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. In your perl program where you will be using your module In your perl program where you will be using your module#!/usr/local/bin/perl use lib ‘ ’ use ModuleName;

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

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

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

27 Thank you Thank you


Download ppt "Introduction to Perl Part III By: Bridget Thomson McInnes 6 Feburary 2004."

Similar presentations


Ads by Google