in reply to Re: capture value from two patterns
in thread capture value from two patterns

It's also ambiguous if all matches fail:

c:\@Work\Perl\monks>perl -wMstrict -le "for (qw(a X b)) { /(a)/ or /(b)/; my $id = $1; print qq{'$_' -> '$id'}; } " 'a' -> 'a' 'X' -> 'a' 'b' -> 'b'

Update 1: Something like
    my $id = $1 // $2 if m!/key/(\d+)|/(\d+)-\d+!;
(if you avoid the problem of the conditionally declared lexical!) does not suffer this:

c:\@Work\Perl\monks>perl -wMstrict -le "for (qw(a X b)) { /(a)|(b)/ or next; my $id = $1 // $2; print qq{'$_' -> '$id'}; } " 'a' -> 'a' 'b' -> 'b'

Update 2: Slight wording change to first sentence.


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

Replies are listed 'Best First'.
Re^3: capture value from two patterns (updated)
by LanX (Saint) on Aug 20, 2020 at 23:37 UTC
    good point, $1 sticks to the last successful match

    so always check before accessing it

    for (qw(a X b)) { my $id = $1 if /(a)/ or /(b)/; print qq{'$_' -> '$id'\n}; }

    C:/Perl_524/bin\perl.exe -w d:/exp/pm_or_regex.pl Use of uninitialized value $id in concatenation (.) or string at d:/ex +p/pm_or_regex.pl line 5. 'a' -> 'a' 'X' -> '' 'b' -> 'b'

    I kept the warning in intentionally.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery