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

Thanks to the forum here I am now aware of how to create and assign variables within an if statement to matched variables. Now I'm trying to set the same variable $m1 with the below statements. Only one pattern will evaluate true at a time, so how do I assign $m1 to only the one that evaluates true without evaluating the other (that seems to clear $m1 if the last pattern evaluated is false)? Thank you as always, the script is coming along perfectly!

Update: In my effort to simplify, I did change one thing, which I believe makes things a bit more difficult; the 3rd matching statement is with a different string(output_2) to pattern match, so I rewrote it correctly below. That said, I believe what will make this work is to somehow only evaluate statements until one is shown to be true, then to breakout with $m1 set

if(my ($m1) = $output =~ /^(pattern1)$/ or my ($m1) = $output =~ /^(pa +ttern2)$/ or my ($m1) = $output_2 =~ /(pattern3)/) { $hash{$key} = $m1; }

Replies are listed 'Best First'.
Re: Match a Variable to Only the True Statement
by AnomalousMonk (Archbishop) on Jan 31, 2016 at 20:31 UTC

    It's not clear to me exactly what you're trying to do, but I wonder if perhaps you need an  | "ordered alternation" operator:

    c:\@Work\Perl\monks>perl -wMstrict -le "my $p1 = qr{ Foo }xms; my $p2 = qr{ Bar }xms; my $p3 = qr{ Zot }xms; ;; my $str = 'Bar'; ;; if (my ($m) = $str =~ m{ \A ($p1 | $p2 | $p3) \z }xms) { print qq{matches: has '$m'}; } " matches: has 'Bar'

    Update:

    my ($m1) = $output =~ /^(pattern1)$/ or my ($m1) = $output =~ /^(pattern2)$/ or my ($m1) = $output =~ /(pattern3)/
    BTW: An expression like the one quoted above, with multiple masking variables (i.e., variables having the same name) defined in the same scope is never a good idea, and Perl would have told you about this ugly situation had you enabled warnings with a  use warnings; statement at the top of your program. Especially for those just starting with Perl, always  use warnings; and  use strict; at the start of your code.


    Give a man a fish:  <%-{-{-{-<

Re: Match a Variable to Only the True Statement
by poj (Abbot) on Jan 31, 2016 at 21:12 UTC
    if ( $output =~ /^(pattern1|pattern2)$/ ){ $hash{$key} = $1; } elsif ( $output_2 =~ /(pattern3)/ ){ $hash{$key} = $1; }
    poj