Subject: | Please add safe_hash_invert |
Often you want to invert a hash (swap keys and values) but just calling
'reverse' will lose data if there are duplicate values. Of course you
can manually check every time you do it, but it would be better to have
a function that encapsulates this and provides a useful error message.
Something like
sub safe_hash_invert {
my %hash = @_;
my %reverse;
foreach my $k (sort keys %hash) {
my $v = $hash{$k};
if (exists $reverse{$k}) {
croak "cannot reverse: $v is mapped to by both $k and
$reverse{$k}\n";
}
$reverse{$k} = $v;
}
return %reverse;
}
Do you agree that it's a good idea for Hash::MoreUtils to provide this?
If so, I will be happy to write a patch with documentation and tests.