Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Appending values to existing hash key

by wind (Priest)
on Mar 21, 2014 at 02:10 UTC ( #1079157=note: print w/replies, xml ) Need Help??


in reply to Appending values to existing hash key

One potential alternative, ensuring keys stay in the same order:
#!/usr/bin/perl use strict; use warnings; my @keys; my %vals; while (<DATA>) { chomp; my @data = split; my $key = join ' ', splice @data, 0, 2; push @keys, $key if !$vals{$key}; push @{$vals{$key}}, join ':', @data; } for (@keys) { print "$_ " . join(', ', @{$vals{$_}}) . "\n"; } __DATA__ id1 name1 cat1 catname1 id1 name1 cat2 catname2 id2 name2 cat3 catname3 id3 name3 cat1 catname1 id3 name3 cat4 catname4
Outputs:
id1 name1 cat1:catname1, cat2:catname2 id2 name2 cat3:catname3 id3 name3 cat1:catname1, cat4:catname4
- Miller

Replies are listed 'Best First'.
Re^2: Appending values to existing hash key
by jaypal (Beadle) on Mar 21, 2014 at 03:41 UTC

    Thanks for the prompt reply. I have to agree, your approach is very clever. Thank you for taking out time to write this alternative solution (a very good one indeed!).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1079157]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2022-12-05 23:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?