0

Possible Duplicate:
concatenate hash values when key is same in perl

I want to store multiple values for a key in hash. For eg:

Input:
SMP00001    HMDB00641
SMP00001    HMDB00051
SMP00001    HMDB00052
SMP00003    HMDB00051
SMP00003    HMDB00517
SMP00004    HMDB00243

Output:
SMP00001: HMDB00641,HMDB00051,HMDB00052
SMP00003: HMDB00051,HMDB00517
SMP00004: HMDB00243

Here is the code I wrote:

push(@{$hash{$smp_id}},$HMDB_id);

When I print the content in hash the output is:

SMP00001 => ARRAY(0x161da40)
SMP00003 => ARRAY(0x11be28)
SMP00004 => ARRAY(0x1265c8)
Community
  • 1
  • 1
I am
  • 1,057
  • 5
  • 14
  • 21
  • Same question had been asked, you can check here for more detailed answer: http://stackoverflow.com/questions/10899977/concatenate-hash-values-when-key-is-same-in-perl. – rahul Aug 11 '12 at 11:38
  • Voting to close as this exact question has been asked several times before – Borodin Aug 11 '12 at 19:41

2 Answers2

2

The values of your hashtable are array references, so you must dereference them to see the elements. That is, instead of

print "$key => $hash{$key}\n";

say

print "$key => @{$hash{$key}}\n";
mob
  • 117,087
  • 18
  • 149
  • 283
1
print "$_: ", join(',', @{$hash{$_}}), "\n" for keys %hash;
cdtits
  • 1,118
  • 6
  • 7