Re: [SPOILER] Re: New Quiz: "What does this code do?" (1-December-2006)

demerphq <[email protected]> Sat, 16 Dec 2006 11:26:24 +0100
Newsgroups gmane.comp.lang.perl.qotw.discuss
Message-ID <[email protected]>
On 12/15/06, Martijn Lievaart <[email protected]> wrote:
> Joshua Kronengold wrote:
>
> >As of 5.8.5, perlre says this:
> >
> >  The numbered match variables ($1, $2, $3, etc.) and the related punctu-
> >  ation set ($+, $&, , , and $^N) are all dynamically scoped until
> >  the end of the enclosing block or until the next successful match,
> >  whichever comes first.  (See "Compound Statements" in perlsyn.)
> >
> >Which on careful analysis (ie, mine, just now :^) would appear to match
> >the  described and tested for behavior -- that, the dynamic scope of
> >numbered match variables expires at the end of their enclosing block,
> >making subroutine calls comparatively safe.
> >
> >As such, the behavior -is- documented -- and can be relied upon when
> >coding for modern perls.
> >
> >
>
> Yes, but I had to read this a few times to really get it. A new match
> can occur in the same block or another block called from within this
> block. If it occurs in the same block, you clobber $n. If it occurs in
> another block, you clobber $n until the end of that block. After that
> block $n is again the previous value.

No, this is wrong. At least as I understand what you have said.

This is what happens:

When a match involving s/// or m// is successful perl localizes an
internal pointer called PL_curpm and sets it to point at the regexp
structure for the most recent match.

At scope exit all vars localized in that scope are rolled back to
their previous values, including ones localized invisibly by the core
such vars like PL_curpm.

The regex magic vars are implemented as ties that access data held in
the structure pointed to by PL_curpm.

Therefore the regex magic vars access the results of the most recently
executed successful match in the current scope.

Yves

-- 
perl -Mre=debug -e "/just|another|perl|hacker/"