Re: [SPOILER] Re: New Quiz: "What does this code do?" (1-December-2006)
Ronald J Kimball <[email protected]> Thu, 14 Dec 2006 11:24:27 -0500
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
On Thu, Dec 14, 2006 at 09:35:57AM -0600, Joshua Kronengold wrote:
> Shlomi Fish writes:
> >When I said that $1 may be destroyed by the param method call, he noted
> >that $1 was locally scoped, which indeed seems to be the case. So my
> >code should be written like that instead.
>
> Wait, what?
>
> This seems wrong -- since $1 is locally scoped, (not lexically
> scoped), it -can- be technically destroyed by the param call, so you
> don't want to do this, even if you can. (if param is written not to
> squash $1, it's bad practice to trust in this).
No, it can't be destroyed by the param call. When the param() exits, $1 is
restored to its previous value, because it is locally scoped.
> However, it seems that at least in modern perls, $1 is -lexically-
> scoped. That seems new. But good:
>
> perl -Mstrict -e 'sub test { shift =~ /b(.*)/ and return $1 }; my
> $str = "abababa"; print +($str =~ /((?:ba){1,2})/ and print
> test($str),"\n") ? $1 : "no","\n"'
> ababa
> baba
I'm not sure what you're trying to show with that code. Here's an example
that shows that $1 is locally, not lexically, scoped:
#!perl
$_ = 'abc';
{
/(a)/;
print "$1\n";
foo();
print "$1\n";
}
sub foo {
print "$1\n";
/(b)/;
print "$1\n";
}
__END__
a
a
b
a
If $1 were lexically scoped, the value it gets within the block wouldn't be
visible in the subroutine, which is outside the block.
Furthermore, although foo() changes the value of $1 to 'b', after it
returns the value of $1 has been restored to 'a'.
So, there's no reason not to write the code as I suggested. :)
Ronald