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