In the OPed code, if $zip is not any value of the hash, $zip_match will not be defined:
(exists will not be appropriate in this case.)c:\@Work\Perl\monks>perl -wMstrict -le "my $zip = '99999'; ;; my %zips = ('City One' => '04321', 'City Two' => '01234'); ;; my ($zip_match) = grep { $zips{$_} eq $zip } keys %zips; print qq{'$zip' not found} if not defined $zip_match; " '99999' not found
Update: The result of the grep operation (one or more matches vs. none) can also be tested directly:
c:\@Work\Perl\monks>perl -wMstrict -le "my $zip = '01234'; ;; my %zips = ('City One' => '04321', 'City Two' => '01234'); ;; if (my ($zip_match) = grep { $zips{$_} eq $zip } keys %zips) { print qq{'$zip' located in '$zip_match'}; } else { print qq{'$zip' not found}; } " '01234' located in 'City Two'
In reply to Re: Hash search and returning by value
by AnomalousMonk
in thread Hash search and returning by value
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |