Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re^3: why is $1 cleared at end of an inline sub?

by haukex (Bishop)
on Sep 17, 2021 at 22:41 UTC ( #11136853=note: print w/replies, xml ) Need Help??

in reply to Re^2: why is $1 cleared at end of an inline sub?
in thread why is $1 cleared at end of an inline sub?

Both of these answers ignored that the sub was an 'anonymous'/'inline' sub

I "ignored" it because it makes no difference, a sub is a sub no matter whether it has an entry in the symbol table or not. (Update: There are small differences, e.g. how a sub call is parsed depending on when the compiler sees the definition, but that's not relevant to this thread.)

... that would have access to surrounding local variables in the same scope, including regex vars.

Sorry, but that's not how dynamic scoping works. It might help to forget about lexical scope entirely for a moment, and to think of it in terms of the call stack: it's like local stores the current value of the variable onto a stack, and exiting the currently executing scope (sub, do, etc.) restores the saved value. This happens during runtime, hence the "dynamic". Also note that dynamic scoping only works for package variables, not lexicals (my).

I had supposed that the '$1' would stay constant until another regex... I would have thought only another regex would change them.

Yes, the implicit dynamic scoping can be little surprising like that, but once you get the hang of dynamic scoping, it should make sense. I showed with my example above why it makes sense to do it that way for regex variables.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2021-10-24 06:59 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (89 votes). Check out past polls.