On Wed, 14 Aug 2002, Jose Malacara wrote:
> Hello. I was wondering if there was a way to open a file into a hash? I know
> this works for arrays, but was wondering if I this could be done for a hash
> also.
>
> I have a file called people.data, which contains two colums:
> jose 2
> karen 8
> jason 9
> tracey 1
>
>
> Can someone tell me what I am doing wrong here:
> =============================================
> #! /usr/bin/perl -w
>
> open (INPUT, "<people.data");
> %people = <INPUT>;
By doing this you are reading all the lines of your file into memory.
This statement finally boils down to
%people = ("jose 2\n","karen 8\n"...);
When you do this the list is evaluated 2 elements at a time with the first
element becoming the hash key and the second the value. Finally your hash
will look this
%people = ( 'jose 9
' => 'karen 8
' ...);
As you can see the odd numbered lines of your file become the hash keys
and the even numbered lines the hash values.
Take a look at Data::Dumper to see the kind of data structure you have
created. perldoc Data::Dumper
This will do what you want
while (<INPUT>) {
my @fields = split; # perldoc -f split
$people{$fields[0]} = $fields[1];
}
> close (INPUT);
>
> #%people = (
> # "jose" => '2',
> # "karen" => '8',
> # "jason" => '9',
> # "tracey" => '1'
> #);
>
> print "The value for jose is $people{jose}\n";
> =============================================
>
> I expect to return the value of "2", but see the following error instead:
>
> "Use of uninitialized value in concatenation (.) or string at ./new.pl line
> 14.
> The value for jose is"
This is because the key jose is not present in your hash and you have
turned warnings on. This is a good thing and also add this line to the
top your script
use strict;
If you want associate a hash with a file take look at
perldoc -f tie
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]