http://www.perlmonks.org?node_id=1055985

LanX has asked for the wisdom of the Perl Monks concerning the following question:

hi

a frequent question in hash and list manipulation leads to grouping of values in sub arrays.

(This week had already two questions which lead to push @{ $h2{$v} } , $k; constructs.)

For instance inverting (i.e. w/o loosing repeated values like with reverse ) of a hash can be done like this

DB<122> sub invert { my ($h)=@_; my %h2; while ( my ($k,$v) = each %$h ) { push @{ $h2{$v} } , $k; } return %h2; } DB<123> @t{a..f}=(1,2)x3 => (1, 2, 1, 2, 1, 2) DB<124> \%t => { a => 1, b => 2, c => 1, d => 2, e => 1, f => 2 } DB<125> invert \%t => (1, ["e", "c", "a"], 2, ["b", "d", "f"])

I took a look into List::MoreUtils and other hash related modules w/o finding a similar solution, even when chaining two or more functional constructs. ( no part from List::MoreUtils doesn't really do )

Do you know any better solutions?

Cheers Rolf

( addicted to the Perl Programming Language)