in reply to Zen and the Art of Match Variables

Thanks. Very informative.

Perhaps I missed it or perhaps I misunderstand how things work, but isn't there a copy operation that happens at run time that you didn't cover? I'm thinking a copying from the outer scope's match variables to the inner scope's match variables (when the inner scope is entered?), but I'm basing this on what I've heard others say not stuff I've investigated myself.

And it seems \$1 gives you a reference to a magic variable that looks up the value using the match variables of the opcode where you dereference it. That would be one way to explain why this code:

$_= "foobar"; /(oo)/; my $out= \$1; my $in; { /(ar)/; $in= \$1; } print "in=out\n" if $in == $out;
prints "in=out". So I'd think the problem with returning a reference to a match variable would be that you'd get the outer scope's matches rather than that the value would be overwritten by subsequent calls to the subroutine.

                - tye

Replies are listed 'Best First'.
Re: Re: Zen and the Art of Match Variables (copy?)
by Elian (Parson) on Mar 25, 2003 at 22:12 UTC
    The inner scope doesn't get a copy of the match variables, rather the optree for the inner scope just has reference to the outer scope match variables--the opnode pointers point to the same memory. (Or they did the last time I looked, though some of this code was touched to fix crashes in Windows forking perl and iThreads for 5.8.0)

    You're right about the references--\$1 makes reference to the magic match variable which always refers to the active first match, as it works its magic by peering at the current optree pointers. I'll go patch that bit up.

      Let me try again.

      In your root node you show how leaving a scope appears to restore the old values of the match variables and explain that this actually happens by virtue of the outer scope's opnodes pointing to a different set of match variables from the inner scope's.

      But this doesn't explain how an inner scope manages to have the same value for match values as the outer scope when they haven't been overwritten. For example:

      for( qw( foobar foobaz ) ) { /(oo)/; { /(ar)/; print "($1) "; } print "[$1]\n"; }
      outputs:
      (ar) [oo] (oo) [oo]
      and your root node explains why "[oo]" is output both times but doesn't explain how "(oo)" could be output.

      That is, how did the inner scope manage to get $1 a value of "oo" when that was set in the outer scope's match variable? I recall hearing that this is done by copying from one set of match variables to the other.

                      - tye