[Israel.pm] Another newbie question - Hashes

Offer Kaye oferk at oren.co.il
Tue Feb 3 23:04:34 PST 2004


>
> 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 :-)
<code>
#!/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
5.6
   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
</code>

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




More information about the Perl mailing list