Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: A regex BR variable dead in following line/command

by haukex (Archbishop)
on Nov 12, 2021 at 14:55 UTC ( [id://11138759]=note: print w/replies, xml ) Need Help??


in reply to A regex BR variable dead in following line/command

The Variables related to regular expressions are (re)set by each successful regex operation and are dynamically scoped, so if you want to use them later, you should generally always store them into other variables, and only use them if the match is successful in the first place. (A related recent thread in regards to the variables' scoping: Re: why is $1 cleared at end of an inline sub?)

Your while($2) is outside of the dynamic scope of the regular expression, which is why it is unset there. Also, using $2 as a loop condition smells a bit fishy - I suspect it may be better if you use the if on the regex to break out of the loop via e.g. last.

Replies are listed 'Best First'.
Re^2: A regex BR variable dead in following line/command
by LanX (Saint) on Nov 12, 2021 at 16:40 UTC
    > Also, using $2 as a loop condition smells a bit fishy

    Indeed, the idiomatic expression is rather

    while( m/REGEX/g ) { ... # use groups only if match successful }

    The only reason to check $2 separately, is to make sure it's not false ( "", 0, undef, etc )

    this can be done with

    while( m/REGEX/g ) { last unless $2; ... }

    tho I doubt the OP is aware of all those false cases.

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-20 00:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found