in reply to How to make a array of hashes and search them

Thanks a ton for the help. I wrote as per the pseudo code. it worked but here the problem is for each and every ID its print same values in all four columns. I have no clue why it is happening.so i need more help.

Thanking you in advance.

Regards

Deepak

foreach $file (@files) { open(INP,"$file") or die "Cannot open file :$!\n"; while (<INP>) { chomp; @line = split "\t",$_; if(exists $trans{$line[0]}) { $array[$j] = $line[1]; $trans{$line[0]} = \@array; } } close(INP); $j++; } foreach $key (keys %trans) { print OUT "$key\t"; foreach(@{$trans{$key}}) { print OUT "$_\t"; } print OUT "\n"; }

Replies are listed 'Best First'.
Re^2: How to make a array of hashes and search them
by moritz (Cardinal) on Feb 17, 2012 at 19:58 UTC

    There seems to be only one global variable with name @array. Thus \@array always returns a reference to the same array, which is probably not what you want.

    The solution is to use strict; and declare your variables in appropriate scopes.

Re^2: How to make a array of hashes and search them
by aaron_baugher (Curate) on Feb 18, 2012 at 02:03 UTC

    As moritz said, your @array appears to be global, so it's not getting recreated each time through your loop, and all your hash keys are getting assigned a reference to the same array. Here's how I'd rewrite your loop to eliminate that array and clarify some things:

    my $j = 0; # file/column number foreach $file (@files){ open(INP,"$file") or die "Cannot open file :$!\n"; while (<INP>){ chomp; my($key,$value) = split "\t"; if(exists $trans{$key}){ $trans{$key}[$j] = $value; } } close(INP); $j++; }

    When you split a line into an array and then start accessing the elements directly like $line[0], that's a good sign you might want to split it into named scalars like $key and $value instead, so you don't have to remember later what array index held what. I think it also makes it easier to see what I'm doing there when I assign the $value to the $j-th element of the array pointed to by the $key of the hash.

    Aaron B.
    My Woefully Neglected Blog, where I occasionally mention Perl.