Another way to think about it is: if you are having to look up values to find keys you have built your hash the wrong way aroung. Hashes are good looking up keys to find values but not so good for looking up values to find keys. So, when you create your hash, swap the keys and values. Then your lookup will be easy.
You can try something like the following:
#!/usr/bin/perl # use strict; use warnings; use Data::Dumper; my %hash1; my %hash2; foreach my $line (<DATA>) { my ($key, $value) = split(/\s+/, $line); push(@{$hash1{$key}}, $value); push(@{$hash2{$value}}, $key); } print Dumper(\%hash1); print Dumper(\%hash2); print "Values for key a are @{$hash1{a}}\n"; print "Keys with value b are @{$hash2{b}}\n"; print "Keys with value h are @{$hash2{h}}\n"; __DATA__ key value a b a c a d e f g h g i j h
Which produces
$VAR1 = { 'e' => [ 'f' ], 'a' => [ 'b', 'c', 'd' ], 'g' => [ 'h', 'i' ], 'j' => [ 'h' ], 'key' => [ 'value' ] }; $VAR1 = { 'c' => [ 'a' ], 'h' => [ 'g', 'j' ], 'b' => [ 'a' ], 'value' => [ 'key' ], 'd' => [ 'a' ], 'f' => [ 'e' ], 'i' => [ 'g' ] }; Values for key a are b c d Keys with value b are a Keys with value h are g j
In reply to Re: get a key for a value revisited
by ig
in thread get a key for a value revisited
by marc.garcia
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |