You are on page 1of 28

Lecture:14

PERL: HASHES, I/O REVISITED, FILEHANDLES

S. S. Paul, CSED, MNNIT

3/7/2011

PART-I

HASHES

INTRO

S. S. Paul, CSED, MNNIT

3/7/2011

One of the most powerful and important feature of Perl  Known as Associative Arrays in olden days  Lazy Programmers Community thought---this was too many letters to type and too many syllables to say  In about 1995--- name changed to hashes


S. S. Paul, CSED, MNNIT

3/7/2011

SCENARIO


 

One limitation of an array=>information contained within it can be difficult to get to. e.g., imagine a list of people & their corresponding ages. @names = qw/ Shreya Mohit Gulshan Micky /; @ages = (20,35,23,41); To get Shreyas age, we just access index 0 of the @ages array But how will you get Mickys age if his name is known rather than his location in the @ages aray?

S. S. Paul, CSED, MNNIT

3/7/2011

SCENARIO CONTD


only way step through @names until we found Micky, & check corresp. age in the @ages array Fine for 4-element array, but for larger(say 40 or 400 or 4000 elements long) ??? If the person was at the end of the list step through 4000 items before we got to the information we wanted The hash solves this problem, very neatly by allowing us to access that @ages array not by an index, but by a scalar key

S. S. Paul, CSED, MNNIT

3/7/2011

HASH SOLUTION
%ages = (Shreya' => 20, Mohit' => 35, Gulshan' => 23, Micky => 41);  Now want to print out Mickys age,access value within the hash using Mickys name as the key:  print Micky is $ages{Micky} years old\n";


S. S. Paul, CSED, MNNIT

3/7/2011

WHY USE A HASH?


General idea is that youll have one set of data related to another set of data.  Hostname, IP address  IP address, hostname  Drivers license number, name  Word, count of number of times that word appears  Username, number of disk blocks they are using: System Administrators favourite


S. S. Paul, CSED, MNNIT

3/7/2011

HASH ELEMENT ACCESS


To access an element of a hash, use syntax that looks like this: $hash{$some_key}  The name of the hash is like any other Perl identifier (letters, digits, and underscores)  but cant start with a digit  When you store something into an existing hash element, it overwrites the previous value


S. S. Paul, CSED, MNNIT

3/7/2011

THE HASH AS A WHOLE


Use the percent sign (%) as a prefix, refer to the entire hash  May be converted into a list, and back again  Assigning to a hash then is a list-context assignment  List expression must have an even number of elements as the hash is made of key-value pairs:  % some_hash = ("aaa","bbb","234.5",456.7);


S. S. Paul, CSED, MNNIT

3/7/2011

UNWINDING THE HASH


The value of the hash (in a list context) is a simple list of key-value pairs:  @any_array = %some_hash;  This is unwinding the hashturning it back into a list of key-value pairs  The pairs wont necessarily be in the same order as the original list


S. S. Paul, CSED, MNNIT

3/7/2011

HASH ASSIGNMENT
A hash may be copied using the obvious syntax:  %new_hash = %old_hash;  This line of code tells Perl to unwind the %old_hash into a list of key-value pairs, then assign those to %new_hash, building it up one key-value pair at a time.  Make an inverse hash:  %inverse_hash = reverse %any_hash;


S. S. Paul, CSED, MNNIT

3/7/2011

THE FAT COMMA


Used for Human-readablity in hash assignment.  A way to pair up keys and values in a list  my %last_name = (Anil => Kumble, Kapil" => Dev, Roger => Bini, Sandeep => Patil, );  Also Known as The Big Arrow


S. S. Paul, CSED, MNNIT

3/7/2011

EXAMPLE


my %last_name = ( "Anil" => "Kumble,


"Kapil" => "Dev",

"Roger" => "Bini, "Sandeep" => "Patil", ); foreach $person(qw < Anil Kapil Roger Sandeep >) { print "I've heard of $person $last_name{$person}.\n"; }

S. S. Paul, CSED, MNNIT

3/7/2011

OUTPUT
o o o o

Ive heard of Anil Kumble. Ive heard of Kapil Dev. Ive heard of Roger Bini. Ive heard of Sandeep Patil.

S. S. Paul, CSED, MNNIT

3/7/2011

HASH FUNCTIONS
The keys Function: keys(%hashname) function yields a list of all the current keys in the hash %hashname.  The values Function: values(%hashname) function returns a list of all the current values of the %hashname.  The each Function: each(%hashname) returns a key-value pair as a two-element list


S. S. Paul, CSED, MNNIT

3/7/2011

HASH FUNCTIONS CONTD


The delete Function:  delete function removes hash elements  operand of delete is a hash reference.  Perl removes key-value pair from the hash. e.g.,  %some_hash = ("aaa","bbb",234.5,34.56); # give %some_hash two elements delete $some_hash{"aaa"}; # %some_hash is now just one key-value pair


S. S. Paul, CSED, MNNIT

3/7/2011

THE %ENV HASH


    

Perl Program runs in an environment. Perl stores this information in the %ENV hash. probably see a PATH key in %ENV: print "PATH is $ENV{PATH}\n"; Depending on OS & platform output may be:
o o

PATH is C:\WINDOWS\system32;C:\strawberry\c\bin; C:\strawberry\perl\site\bin;C:\strawberry\perl\bin

OR
o

PATH is /usr/local/bin:/usr/bin:/sbin:/usr/sbin

Part II

I/O REVISITED

S. S. Paul, CSED, MNNIT

3/7/2011

INPUT FROM STDIN




Reading from standard input (via the Perl filehandle called STDIN) is easy $a = <STDIN>; # read the next line up to a newline, or whatever $/ set to. Perl automatically copies the line that is read into the $_ variable. while (<STDIN>) { chomp; # like "chomp($_)" # other operations with $_ here }

S. S. Paul, CSED, MNNIT

3/7/2011

INPUT FROM THE DIAMOND OPERATOR Unlike <STDIN>, the diamond operator gets its data from the file or files specified on the command line  Technically, the diamond operator works from the @ARGV array  @ARGV = ("aaa","bbb","ccc"); while (< >) { # process files aaa, bbb, and ccc print "this line is: $_"; }


S. S. Paul, CSED, MNNIT

3/7/2011

OUTPUT TO STDOUT
Using print for Normal Output:  The print function takes a list of strings and sends each string to standard output in turn  print (2+3),"hello"; # wrong! prints 5, ignores "hello" print ((2+3),"hello"); # right, prints 5hello print 2+3,"hello"; # also right, prints 5hello


S. S. Paul, CSED, MNNIT

3/7/2011

OUTPUT TO STDOUT CONTD..


 

Using printf for Formatted Output: The printf function takes a list of arguments (enclosed in optional parentheses) The first argument is a format control string


o

printf "%15s %5d %10.2f\n", $s, $n, $r ;


prints $s in a 15-character field, then space, then $n as a decimal integer in a 5-character field, then another space, then $r as a floating-point value with 2 decimal places in a 10-character field, and finally a newline.

Part III

INTRODUCTION TO FILEHANDLES

S. S. Paul, CSED, MNNIT

3/7/2011

WHAT IS A FILEHANDLE?


 

A filehandle in a Perl program is the name for an I/O connection between your Perl process and the outside world. STDIN is a filehandle, naming the connection between the Perl process and the UNIX standard input(or DOS prompt?) filehandles are used without a special prefix character Recommendation: use ALL UPPERCASE letters in your filehandle to avoid confusion with other similar terms in the same namespace.

S. S. Paul, CSED, MNNIT

3/7/2011

OPENING A FILEHANDLE


  

Perl provides three filehandles, STDIN, STDOUT, and STDERR automatically open to files or devices established by the program's parent process (probably the shell) open function to open additional filehandles. The syntax looks like this: open(FILEHANDLE,"somename"); where FILEHANDLE is the new filehandle and somename is the external filename

S. S. Paul, CSED, MNNIT

3/7/2011

CLOSING A FILEHANDLE


All forms of open return true for success and false for failure

When you are finished with a filehandle, you may close it with the close operator, like:  close(FILEHANDLE);


S. S. Paul, CSED, MNNIT

3/7/2011

USING FILEHANDLES
Once a filehandle is open for reading, ONE can READ lines from it just as ONE can read from standard input with STDIN.  e.g., to read lines from the password file:  open (EP,"/etc/passwd"); while (<EP>) {chomp; print "I saw $_ in the password file!\n"; }


S. S. Paul, CSED, MNNIT

3/7/2011

THANK YOU

You might also like