Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have seen this somewhere but can't seem to find it again. I want to find out which condition was met (in either if or unless..)

for example :
if ($input{info1} || $input{info2} || $input{info3}) { print "information is valid for <this is where I want to put wh +ich part of the if condition was met.. instead of rechecking again he +re."> } else { print "none of the conditions were met\n"; }
Thanks for help!

Replies are listed 'Best First'.
Re: a simple question...
by wind (Priest) on Nov 28, 2007 at 17:26 UTC
    if (my @matches = grep {$input{$_}} qw(info1 info2 info3)) { print "Matched: @matches"; } else { print "none of the conditions were met\n"; }
    - Miller
      Oh that's what I want. Would @matches have $_ info? or the value of $input{$_} ?


      Thanks!
        @matches would contain the keys of the hash that matched. If all you care about are the values, then use this construct:
        if (my @values = grep {$_} @input{qw(info1 info2 info3)}) { print "Matched values: @values"; } else { print "none of the conditions were met\n"; }
        But then again, you could continue to match keys, and use a slice to access the values inside the if. It all depends on what your needs are.
        if (my @matches = grep {$input{$_}} qw(info1 info2 info3)) { print "Matched keys: @matches"; print "Matched values: @input{@matches}"; } else { print "none of the conditions were met\n"; }
        - Miller

        grep would give you 'info1', for example. If you want $input{$_}, use map instead.

        - tye        

Re: a simple question...
by FunkyMonk (Bishop) on Nov 28, 2007 at 17:25 UTC
    Why don't you capture the result of the test in a variable, like so...
    if (my $matched = $input{info1} || $input{info2} || $input{info3}) { print "information is valid for $matched." } else { print "none of the conditions were met\n"; }

Re: a simple question...
by Nkuvu (Priest) on Nov 28, 2007 at 17:29 UTC

    Just tried this simple script:

    use strict; use warnings; my (%info, $quack); # If this is commented out, "no quack" $info{baz} = 3; # Assignment intentional in conditional if ($quack = $info{foo} or $quack = $info{bar} or $quack = $info{baz}) + { print "Quack is $quack\n"; } else { print "No quack\n"; }

    Prints "Quack is 3".

      well rather than getting Quack is 3, I want it to say Quack = baz. Is that possible?

        Then it looks like wind's reply is more along the lines of what you want.