Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverting a Hash's Key and Values in Perl

Tags:

hash

perl

I would like to make the value the key, and the key the value. What is the best way to go about doing this?

like image 756
Steffan Harris Avatar asked May 25 '11 18:05

Steffan Harris


People also ask

How do I reverse a hash in Perl?

%nhash = reverse %hash; Note that with reverse, duplicate values will be overwritten. the reverse way is nice, but it has some cavets (pasted directly from the perl docs): If a value is duplicated in the original hash, only one of those can be represented as a key in the inverted hash.

How do I save a key value pair in Perl?

A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..

How do I print a key in Perl?

We can done this by using map function. map {print "$_\n"} keys %hash; map function process its statement for every keys in the hash. The map function is there to transform a list.


2 Answers

Adapted from http://www.dreamincode.net/forums/topic/46400-swap-hash-values/:

Assuming your hash is stored in $hash:

while (($key, $value) = each %hash) {    $hash2{$value}=$key; }  %hash=%hash2; 

Seems like much more elegant solution can be achieved with reverse (http://www.misc-perl-info.com/perl-hashes.html#reverseph):

%nhash = reverse %hash; 

Note that with reverse, duplicate values will be overwritten.

like image 61
jsalonen Avatar answered Oct 02 '22 11:10

jsalonen


Use reverse:

use Data::Dumper;  my %hash = ('month', 'may', 'year', '2011'); print Dumper \%hash; %hash = reverse %hash; print Dumper \%hash;
like image 45
fvox Avatar answered Oct 02 '22 12:10

fvox