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

Re: Inverting a hash safely

Thread Previous | Thread Next
From:
Jenda Krynicky
Date:
August 3, 2009 08:03
Subject:
Re: Inverting a hash safely
Message ID:
4A771813.12128.144969B4@Jenda.Krynicky.cz
From: Ed Avis <eda@waniasset.com>
> 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.

Jenda
===== Jenda@Krynicky.cz === http://Jenda.Krynicky.cz =====
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


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About