As already mentioned by Borodin in the comments, there is no direct way to accomplish this. But you could do it in the following way:
sub getKeyByValue {
my ($hashref, $val) = @_; # get sub arguments
for (keys %$hashref) {
# find key by value and give back the key
return $_ if grep $_ eq $val, @{$hashref->{$_}};
}
return undef; # value not found
}
my $key = getKeyByValue(\%hash, 'banana');
print $key;
Output: fruit
Just give the hash reference and your desired value to the subroutine getKeyByValue() and it will return the corresponding key. If the value can't be found, the subroutine will return the undefined value undef. If your data structure is really big, this trivial search is obviously not the most efficient solution.
Note: If the value banana is stored several times (under more than one key), then this subroutine will of course only return the first random match (key). You have to modify the subroutine if you are interested in all the keys under which banana is possibly stored.
There are many ways to do this, like most of the time in Perl. For example you could reverse the hash and create a new one (see example in perlfaq4).
numbersorfruitas values.forloop, or usingmapas in the answer below.