in reply to capture value from two patterns

TIMTOWTDI

that's IMHO the shortest and most intuitive

DB<35> $_='a' DB<36> ; /(a)/ or /(b)/; $x= $1 DB<37> p $x a DB<38> $_='b' DB<39> ; /(a)/ or /(b)/; $x= $1 DB<40> p $x b DB<41>

I'm aware you wanted the list assignment approach, but it's longer because you'd need to repeat ($x) = for each term and I prefer DRY idioms.

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

Replies are listed 'Best First'.
Re^2: capture value from two patterns (updated)
by AnomalousMonk (Archbishop) on Aug 20, 2020 at 22:31 UTC

    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:  <%-{-{-{-<

      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