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


in reply to Re: inverting hash / grouping values
in thread inverting hash / grouping values

> Have you looked at the safe_reverse function in Hash::MoreUtils?

Yes I looked - but I didn't install to try ... hmm thanks!

IMHO the documentation is quite misleading ...

Returns safely reversed hash (value, key pairs of original hash). If no BLOCK is given, following routine will be used:

(value,key pairs ???)

... and better examples showing in and output are lacking.

After looking at it I was unhappy about the blocked namespace, a module called Hash::MoreUtils could offer much more.

Cheers Rolf

( addicted to the Perl Programming Language)

update

After diving into the code, it looks like safe_reverse will not represent unique values as 1-element-arrays but as scalars.

update

This partly explains my confusion, this function works like a normal reverse if all values are unique.

DB<100> use Hash::MoreUtils qw/safe_reverse/ DB<101> @h{a..c}=1..3 => (1, 2, 3) DB<102> safe_reverse \%h => (1, "a", 3, "c", 2, "b") DB<105> @h{a..c}=(1,1,2) => (1, 1, 2) DB<106> safe_reverse \%h => (1, ["a", "b"], 2, "c")

to be able to have the same effect like invert in the OP one needs to write

DB<110> safe_reverse sub { my ($k, $v, $r) = @_; return [ @{$r->{$v} +}, $k ] },\%h => (1, ["a", "b"], 2, ["c"])