in reply to Re: Hash search and returning by value
in thread Hash search and returning by value

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?

Replies are listed 'Best First'.
Re^3: Hash search and returning by value
by LanX (Saint) on Dec 09, 2014 at 16:08 UTC
    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 ☆☆☆☆ :)

Re^3: Hash search and returning by value
by AnomalousMonk (Archbishop) on Dec 09, 2014 at 16:25 UTC
    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.