The following idiom works pretty well:
my @keys = grep { $hash{$_} eq $value } keys %hash;
Con: It doesn't scale nicely if you plan on doing a number of times.
If you want to iterate over the hash by value, you could create a hash whose keys are the values of the original hash and whose values are arrays of the keys of the original hash having those values. The following code creates this hash and displays it:
my %reverse_hash; push{@{$reverse_hash{$hash{$_}}}, $_); foreach keys %hash; print(join(', ', @{$reverse_hash{$_)}), "\n"); foreach keys %reverse_hash;
Con: Assumes the values are strings.
Con: If you make any changes to %hash, you need to recompute %reverse_hash.
There's probably a module (using a tied hash) which provides an efficient solution by maintaining two hashes internally (one indexed by key, and one indexed by value).
Update: Found Tie::Hash::TwoWay
In reply to Re: Hashes: Obtaining the Key Value for a Given Value Value
by ikegami
in thread Hashes: Obtaining the Key Value for a Given Value Value
by o2bwise
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |