in reply to Re: grep value in hash
in thread grep value in hash

Alternately if this is something you need to do often build an inverted hash with the keys and values switched.

my %hash_inverted; @hash_inverted{ values %hash } = keys %hash;

Just remember that this won't be automagically updated so if you update %hash you'll need to also update %hash_inverted (and/or wrap them both up in an object and let that keep things updated for you when you use its accessors).

Update: Good point below about duplicates, which also brings up the point that if your original hash has non-scalar values you may need something like Tie::RefHash for the inverted version.

Replies are listed 'Best First'.
Re^3: grep value in hash
by revdiablo (Prior) on Feb 17, 2006 at 16:43 UTC

    Another issue to be aware of is duplicate values. This can be handled by doing a bit more work with the inversion:

    my %hash_inverted; for (keys %hash) { my $value = $hash{$_}; push @{ $hash_inverted{$value} }, $_; }

    This way each value in the inverted hash will be an array reference, which contains all the keys that value corresponds to.