Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: capture value from two patterns (updated)

by AnomalousMonk (Bishop)
on Aug 20, 2020 at 22:31 UTC ( #11120944=note: print w/replies, xml ) Need Help??


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 (Cardinal) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11120944]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2020-10-20 09:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (209 votes). Check out past polls.

    Notices?