Thursday, February 11, 2010

inverting a hash

Code I've written in the past to swap keys and values

my %hash = ( foo => bar, ... fee=>fo);
my %reversed_hash;
foreach my $key (keys %hash) {
$reversed_hash{$hash{$key}} = $key;

or... I could have just done this all along.
%hash = reverse %hash;

When you think of how this works by treating the hash as an array of key/value pairs then just reversing the order of the array, it initially feels somehow "dirty". But give it a few minutes and you realize it's really a frickin elegant solution!


  1. provided your hash length is in even numbers, or else, everything will get screwed up ..... ewwwww ;p

  2. @lionel319, why does hash length matter? A hash has by definition an even number of things (that's why we call them key-value *pairs*).