Yes, this:
$matching_key=grep { $_ =~ /$regex/ } keys %tax2loc;
... returns the number of matching keys. If you want to get the actual text of the key, you need to call grep in list context:
@all_matching_keys = grep { $_ =~ /$regex/ } keys %tax2loc; $matching_key = $all_matching_keys[0];
If you only care about the first match, then you can simply parenthesise $matching_key like this:
($matching_key) = grep { $_ =~ /$regex/ } keys %tax2loc;
The parentheses force list context on the assignment, and thus on grep.
That said, the above code is wasteful. If the very first key happens to match the regexp, then Perl will still waste time checking every key in %tax2loc. Using first from List::Util will probably be more efficient.
$matching_key = first { $_ =~ /$regex/ } keys %tax2loc;
Also note that "$_ =~" is totally superfluous here. You could just do:
$matching_key = first { /$regex/ } keys %tax2loc;
In reply to Re: grep keys in hash and retrieve values
by tobyink
in thread grep keys in hash and retrieve values
by AWallBuilder
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |