Jun 22, 2008

How to reverse hash or Lookup a hash by value instead of key

But remember keys are uniue but values are not, so before reversinf the
original array values should be unique, after reverse these values become
keys of reversed array. Otherwise things will not work out in ur way.
Anyways just give a try
# Eg: %hash = ( a => 10, b => 10, c => 10, d => 10);

Example1:
#########
#!F:\Perl\bin\perl -w
use Data::Dumper;

# The following is good and easy to use but not tat much efficient in terms of space,
as it needs to keep a copy of the hash.

%hash = ( a => 10, b => 20, c => 30, d => 40);
print "\n Hash before reverse:", Dumper(\%hash);

%reverse = reverse %hash; # It will reverse the hash

print "\n Hash after reverse :", Dumper(\%reverse);
print "\n";


Example2:
#########
#!F:\Perl\bin\perl -w
use Data::Dumper;

# The following is sapce efficient

%hash = ( a => 10, b => 20, c => 30, d => 40);
print "\n Hash before reverse:", Dumper(\%hash);
while (($key, $value) = each %hash) {
$hash{$value} = $key;
}
print "\n Hash after reverse :", Dumper(\%hash);
print "\n";

No comments:

Post a Comment