I would like to make the value the key, and the key the value. What is the best way to go about doing this?
%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.
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..
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.
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.
Use reverse
:
use Data::Dumper; my %hash = ('month', 'may', 'year', '2011'); print Dumper \%hash; %hash = reverse %hash; print Dumper \%hash;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With