develooper Front page | perl.beginners | Postings from August 2009

Re: Inverting a hash safely

Thread Previous | Thread Next
Jenda Krynicky
August 3, 2009 08:03
Re: Inverting a hash safely
Message ID:
From: Ed Avis <>
> My question is, does there exist a 'safe hash invert' function in some CPAN
> module?  I was imagining something like
>     my %hash = (a => 1, b => 2);
>     my %reverse = safe_hash_invert %hash; # works fine
>     $hash{c} = 1;
>     %reverse = safe_hash_invert %hash; # throws an error 'duplicate values...'
> I see Hash::Util and Hash::MoreUtils on CPAN but neither provides such a
> function.  Before I write one myself I wanted to check if there is already
> a standard implementation.

I don't think there is and I don't think there's a need.

my %hash = (a => 1, b => 2,
 c => 1,
my %reverse = reverse %hash;
die "Bummer, the values were not unique!"
 if keys(%hash) != keys(%reverse);

Complex, was it? :-)

As the test whether the values are unique would have to build a hash 
of the values, there's no point in testing first and then building 
the reverted hash.

===== === =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
	-- Terry Pratchett in Sourcery

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About