-
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
| [reply] [d/l] [select] |
Thanks, ikegami.
I'm all set!
Tony
| [reply] |
I think you just want to sort the keys based on the values:
for my $k (sort { $hash{$a} <=> $hash{$b} } keys %hash) {
print "$k: $hash{$k}\n";
}
There's a module, Sort::Key, for doing it faster, though it likely won't matter.
Caution: Contents may have been coded under pressure.
| [reply] [d/l] |
Thanks, Roy.
I used your snippet of code. That's sweet!
I'm all set.
Tony
| [reply] |