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

Re: Inverting a hash safely

Thread Previous | Thread Next
Ed Avis
August 4, 2009 02:40
Re: Inverting a hash safely
Message ID:
Shawn H. Corey <shawnhcorey <at>> writes:

>But then again I never have to invert a hash; when I populate it, I 
>would populate its inverse as well.  I would build both data structures 
>at the same time, inserting only the data I need, where I need it.

That's often a good approach.  But in the particular case I was thinking of,
there was some (programmer-maintained, not user-maintained) configuration data
in a hash:

    my %lookup = (Frob => 55, Boo => 66, Grick => 67);

Of course it would be silly to write a %lookup_reverse hash by hand and then
worry about keeping the two consistent.  Better to write it once and invert it.

Similarly, if you are making a subroutine that takes a hash as input, it is
inconvenient to require your caller to pass both the hash and its inverse.
Indeed, it creates all sorts of opportunities for bugs when somehow the hash
and inverse-hash you are passed aren't consistent with each other.  (Generally
anything that can go wrong will go wrong, sooner or later.)

Or if your routine gives a hash as output (such as many XML processing or
database modules), it would be seen as a bit weird to return both a hash and
an inverse-hash.  It's a question of taste, but I would prefer to just get one
hash as the return value, and invert it if I need to.

So I don't think it is fair to say that inverting a hash is never needed,
although you can certainly minimize the need for it if you build your own
data structures carefully.

Ed Avis <>

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