Skip Menu |

This queue is for tickets about the Hash-MoreUtils CPAN distribution.

Report information
The Basics
Id: 48403
Status: resolved
Priority: 0/
Queue: Hash-MoreUtils

People
Owner: Nobody in particular
Requestors: EDAVIS [...] cpan.org
Cc:
AdminCc:

Bug Information
Severity: Wishlist
Broken in: 0.01
Fixed in: 0.02



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.
I added a safe_reverse function guided by slice_grep and hashsort. Let me know if it fit's your needs.
0.02 uploaded to CPAN
Thank you for adding safe_reverse. By default it will return a hash mapping (v -> ks) where ks is either a single scalar key from the original hash or a listref to several keys. This will often be useful. However, I think the more common case is to reverse a hash which is expected to have a 1-1 mapping from keys to values. In other words, to die with an error if the same value appears under two keys. This can be done by calling safe_reverse with the croak_dup subroutine given in the pod documentation. I think it would be useful to provide that as a library routine, not just as code to copy and paste. Could you add safe_reverse_single which reverses and croaks on duplicates?