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 ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.