O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Inverting a Hash

Problem

Hashes map keys to values. You have a hash and a value for which you want to find the corresponding key.

Solution

Use reverse to create an inverted hash whose values are the original hash’s keys and vice versa.

# %LOOKUP maps keys to values
%REVERSE = reverse %LOOKUP;

Discussion

This technique uses the list equivalence of hashes mentioned in the introduction. In list context, reverse treats %LOOKUP as a list and reverses the order of its elements. The significant property of a hash treated as a list is that the list elements come in pairs: the first element is the key; the second, the value. When you reverse such a list, the first element is the value, and the second is a key. Treating this list as a hash results in a hash whose values are the keys of the original hash and vice versa.

Here’s an example:

%surname = ( "Mickey" => "Mantle", "Babe" => "Ruth" );
%first_name = reverse %surname;
print $first_name{"Mantle"}, "\n";

                  Mickey

When we treat %surname as a list, it becomes:

("Mickey", "Mantle", "Babe", "Ruth")

(or maybe ("Babe", "Ruth", "Mickey", "Mantle") because we can’t predict the order). Reversing this list gives us:

("Ruth", "Babe", "Mantle", "Mickey")

When we treat this list as a hash, it becomes:

("Ruth" => "Babe", "Mantle" => "Mickey")

Now instead of turning first names into surnames, it turns surnames into first names.

Example 5.2 is a program called foodfind . If you give it a food name, it’ll tell you the color of that food. If you give it a color, it’ll ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required