in reply to Re^2: Appending values to existing hash key
in thread Appending values to existing hash key

Hi jaypal,
i totally agreed with ++NetWallah and really you can use a map for the nested for loop like so:

use warnings; use strict; my %hash; while (<DATA>) { my @data = split; push @{ $hash{ $data[0] }{ $data[1] } } => "$data[2]: $data[3]"; } for my $key ( sort keys %hash ) { print $key, ' ', join( ', ' => map { $_, @{ $hash{$key}{$_} } } keys %{ $hash{$ke +y} } ), $/; } __DATA__ id1 name1 cat1 catname1 id1 name1 cat2 catname2 id2 name2 cat3 catname3 id3 name3 cat1 catname1 id3 name3 cat4 catname4


UPDATE: Code updated as indicated by NetWallah.

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me

Replies are listed 'Best First'.
Re^4: Appending values to existing hash key
by NetWallah (Canon) on Mar 21, 2014 at 04:47 UTC
    The statement :
    join( ', ' => map { $_, @{ $hash{$key}{$_} } } keys $hash{$key} ), +$/;
    should read:
    join( ', ' => map { $_, @{ $hash{$key}{$_} } } keys %{ $hash{$key} +} ), $/;
    Nice shortcut (++) - nesting the hashes !

            What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?
                  -Larry Wall, 1992

      Thanks NetWallah for the extra eye! Staying up too late with C is not helping! And so do perl version 5.16.1! Am downgrading to v5.8.1! Lol :)

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me
Re^4: Appending values to existing hash key
by jaypal (Beadle) on Mar 21, 2014 at 04:31 UTC

    Wow, you guys are totally awesome. My first post (albeit lame) has got me so many great tricks and tips. Reading the map function initially from the camel book was a little overwhelming for me. But your usage in an example below has started my brain to make some sense out of it. Another valuable and code shortening gem you have offered is

    push @{ $hash{ $data[0] }{ $data[1] } } => "$data[2]: $data[3]";
    Thank you so much!