in reply to uninitialized value on hash lookup (was: hash problem)

Let me reformat your code a little bit in order to make its purpose clear:
#!/usr/bin/perl -w use strict; my %myhash=(); my $myhash; open(DATA_LIST, "<data_list") or die "Can't open data_list to read!: $ +!\n"; while (<DATA_LIST>){ chomp; my ($Line,$Filed,$Dvalue)=split/\t/; #open(MYHASH, ">myhash") or die "Can't open myhash to write : $!\n"; # vladb: reading data from file 'file_data' into %myhash hash.. do_hash("file_data"); # vladb: are you absolutely sure value stored in $Line # was also found in the 'file_data' file which was used to # initialize the %myhash hash structure? print $myhash{$Line},"\n"; # *** vladb: move this line inside the f +ollowing if(..){} block. if (exists $myhash{$Line}){ print $Filed,"\t ",$Dvalue,"\t", $myhash{$Line},"\n"; } } sub do_hash { my ($filename)=@_; open(FH, $filename) or die "Can't open $filename: $!\n"; while(<FH>){ chomp; my ($Name, $Data)=split/\t/; $myhash{$Name}=$Data; } close FH; }
Please refer to my comments inside your code. The problem here, essentially, is that you are reading records from 'file_data' file and storing them in a global %myhash hash structure such that the first field of each record is your hash key, while the second field is your value. However, as you read records (lines) from the 'data_list' file and use the first field value (stored in the $Line) variable to reference a value in the %myhash hash, there's no absolute guarantee that the hash contains a matching key in the first place. One suggestion would be to move the print $myhash{$Line},"\n"; line inside the if block that follows. This way, you'll never attempt to access a hash record via a non-existant key.

UPDATE: Dear, Anonymous Monk you have to absolutely check for a key to exist in a hash before actually using it to retrieve any data from that hash. Therefore, to avoid the kind of error you were getting, my suggestion would be to move the line marked with '***' inside your if block where you check for the key to 'exist' before using it...

_____________________
$"=q;grep;;$,=q"grep";for(`find . -name ".saves*~"`){s;$/;;;/(.*-(\d+) +-.*)$/;$_=&#91"ps -e -o pid | "," $2 | "," -v "," "&#93;`@$_`?{print" ++ $1"}:{print"- $1"}&&`rm $1`;print"\n";}

Replies are listed 'Best First'.
Re: Re: hash problem
by Anonymous Monk on May 21, 2002 at 17:04 UTC

    Thank you for your help!
    My first file is a table:
    Line Field Dvalue
    a123 A1 12.83
    a124 A1 9.68
    ...
    and second file is a table too:
    Name Data
    a123 acgt...(whole sequence)
    a124 catt...
    both table all use tab to separate each column. Please help!
Re: Re: hash problem
by Anonymous Monk on May 21, 2002 at 18:54 UTC
    Thanks, If I put this line inside the following if(..){} block.: print $myhash{$Line},"\n"; it will hanging there, gives you nothing and never exit at all. which just like I do not have this line and program go directly to if (..) {} block.