[Israel.pm] Another newbie question - Hashes

Prager, Mark Mprager at ndsisrael.com
Wed Feb 4 00:13:15 PST 2004

Thanks to All -
My scripts are now working nicely.


|-----Original Message-----
|From: perl-bounces at perl.org.il [mailto:perl-bounces at perl.org.il]On
|Behalf Of Offer Kaye
|Sent: Wednesday, February 04, 2004 9:05 AM
|To: Perl in Israel
|Subject: RE: [Israel.pm] Another newbie question - Hashes
|> I am trying to read in input file into a hash -
|> i.e
|> File:
|> 3 a
|> 4 ssd
|> 5 fg
|> 67 aa
|> 654 lp
|> would go into a hash indexed by the first column.
|> I know we did this in the course - but for the life of me, I
|> cannot find it in my
|> notes..
|> Best Regards,
|> Mark Prager
|Since everyone else (except for Yosef, and his answer is too 
|golf'ish) used
|a split, here's my version, not split based and newbie friendly :-)
|#!/usr/bin/perl -w
|use strict; # always a good idea to work under "-w" and "use strict"
|my $input_file = "aaa"; # your input file name
|my %hash;               # predeclare your hash.
|my $line;
|open(IN,$input_file) or die "Couldn't open $input_file for 
|reading: $!\n"; #
|always check your file could be opened
|while (defined ($line = <IN>)) { # this code will also work 
|for perl before
|   next unless $line =~ m/^\s*(\w+)\s+(\w+)/; # jump over 
|empty lines and
|get the two columns saved at the same time
|   $hash{$1} = $2; # assign the two columns as the hash key and value
|close(IN) or die "Couldn't close $input_file after reading: 
|$!\n"; # always
|check your file could be closed
|Depending on how sure you are of the format of the input file, you can
|change the regular expression I used to cover more edge cases 
|and illegal
|input. However if you are sure of the format (e.g. the input 
|file is itself
|produced by some script), this code should work nicely.
|Hope this helps :-)
|Offer Kaye
|Perl mailing list
|Perl at perl.org.il
Information contained in this email message is intended only for use of the individual or entity named above. If the reader of this message is not the intended recipient, or the employee or agent responsible to deliver it to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please immediately notify the postmaster at ndsisrael.com and destroy the original message.

More information about the Perl mailing list