on Wed, 14 Aug 2002 07:35:29 GMT, [EMAIL PROTECTED] (Jose Malacara)
wrote: 

> 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>;
> close (INPUT);
> 
> 
> 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"

It is useful to analyze what's happening when you execute your 
program:

When you write '%people = <INPUT>;", <INPUT> is evaluated in list 
context, meaning that <INPUT> will produce a list consisting of all 
the lines in your input-file. This list looks as follows (I removed 
some whitespace for brevity):

    ("jose 2\n", "karen 8\n", "jason 9\n", "tracey 1\n")

(Also note the presence of the newlines).

When you assign this list to the %people hash, you take (key,value)-
pairs from this list, so you will have:

    $people{"jose 2\n" } = "karen 8\n";
    $people{"jason 9\n"} = "tracey 1\n";

Which is not what you want.

The following program will do what you want:

    #!/usr/bin/perl -w
    use strict;

    my %people = ();
    open (INPUT, "<people.data") or die "Cannot open file: $!";

    while(my $line = <INPUT>) {
        chomp($line); # remove trailing "\n"
        my ($name, $number) = split " ", $line;
        $people{$name} = $number;
    }
    close (INPUT);

    print "The value for jose is $people{jose}\n";

The main part of the program is in the while loop, where we read each 
line in succession (until there are no more lines), remove the 
trailing newline, and then split this line into a name and number 
part, which we then feed to the hash.

-- 
felix

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to