On Mon, Jul 21, 2003 at 02:18:48PM -0400, Bob Showalter wrote:
> Steve Grazzini wrote:
> > On Mon, Jul 21, 2003 at 10:34:59AM -0400, Jeff 'japhy' Pinyan wrote:
> > > The documentation states that the $DIGIT variables are set after
> > > each SUCCESSFUL pattern match.
> > 
> > The docs also claim that the digit variables will be "dynamically
> > scoped to the current BLOCK", which isn't quite accurate, and is
> > presumably what confused Ed. 
> 
> The docs are correct. $1 is dynamically scoped to the block. Ed's code
> didn't leave the block, so this dynamic scoping didn't apply.

[ snip well-behaved example ]
 
> Thus, $1 is saved before entry to the block and restored afterward.

You can't prove that there isn't a bug by showing well-behaved
examples!  :-)

First: the digit variables are supposed to be dynamically scoped,
but really they're not scoped at all.  Compare these two examples,
which, according to perlvar, ought to be equivalent.

    # local()ized variable -----------------

    our $x = 0;

    sub F {
      local $x = $x + 1;
      print $x;
      F() if $x<2;
      print $x;
    }

    F();    # prints "1221"


    # digit variable ------------------------

    "0" =~ /(\d)/;

    sub F {
      ($1 + 1) =~ /(\d)/;
      print $1;
      F() if $1<2;
      print $1;
    }

    F();    # prints "1222"

Now, you can almost explain this by saying that Perl's notion of the
"last match" is dynamically scoped, and that the digit variables just
refer to captured substrings from the last match.

[ Which leaves out a crucial part of the explanation, but at least 
  it's almost correct. ]

But then there's a second problem: the notional "last match" isn't
scoped to the body of the loop either.

    #-- local()ized variable ------------------

    our $x = 1;
    print $x;

    for (1..3) {
      local $x = $x + 1;
      print $x;
    }

    print $x;   # output is "12221"

    #-- digit variable ------------------------

    "1" =~ /(\d)/;
    print $1;

    for (1..3) {
      ($1 + 1) =~ /(\d)/;
      print $1;
    }

    print $1;   # output is "12341"

The actual behavior is more like what you said: the "last match"
is saved before loop entry and restored loop exit.  But that's a bit
of a cheat, since everything else that we call "dynamically scoped"
would get saved and restored with each iteration.

-- 
Steve

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to