in reply to Hash search and returning by value

If you're going to do that often, and you can't have two cities with the same zip code, you can reverse the hash like this: my %reversed = reverse %zips; and then try exists $reversed{$zip}. Or you can grep on the values instead of the keys: grep { $_ eq $zip } values %zips;

Replies are listed 'Best First'.
Re^2: Hash search and returning by value
by Anonymous Monk on Dec 09, 2014 at 16:04 UTC
    Yes, it worked:
    use strict; use warnings; my $zip = '01234'; my %zips = ( "City One" => "04321", "City Two" => "01234", ); my ($zip_match) = grep { $_ eq $zip } values %zips; print "\n $zip_match\n"; # 01234

    Can "grep" take a condition, like only assign to "$zip_match" if it is true?
      Without parens on the LHS you'll call grep in scalar context and get the number of matches returned.

      Only 0 matches is false.

      But you should really take reverse into consideration to create an inverted hash.

      Cheers Rolf

      (addicted to the Perl Programming Language and ☆☆☆☆ :)

      Can "grep" take a condition, like only assign to "$zip_match" if it is true?

      In the statement
          my ($zip_match) = grep { $_ eq $zip } values %zips;
      the condition grep takes is  $_ eq $zip and it matches in list context, so it returns nothing (the empty list) if there is no match and assigns nothing to  $zip_match which retains the uninitialized value (i.e., undef) with which it was created.