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

Ronald J Kimball <[email protected]> Thu, 14 Dec 2006 13:34:57 -0500
Newsgroups gmane.comp.lang.perl.qotw.discuss
Message-ID <[email protected]>
On Thu, Dec 14, 2006 at 10:28:11AM -0800, Ben Prew wrote:
> On 12/14/06, Ronald J Kimball <[email protected]> wrote:
> >It's exactly the same behavior as you would get by using local() on a
> >regular variable.  The value is visible outside the block, but when the
> >block exits the previous value is restored.  If it were lexically scoped,
> >the value would not be visible outside the block.
> 
> Actually, I agree with Josh, the local() method introduces dynamic
> scope, so it would behave very differently.  ex
> #!/usr/bin/perl
> 
> local $foo;
> $foo = 'bar';
> warn $foo;
> baz();
> warn $foo;
> 
> sub baz
> {
>        warn $foo;
>        $foo = 'blah';
>        warn $foo;
> }
> 
> prints:
> 
> bar at test.pl line 5.
> bar at test.pl line 11.
> blah at test.pl line 13.
> blah at test.pl line 7.
> 
> But, it sounded like you would have expected:
> 
> bar, bar, blah, bar....

Yes, I would have expected bar, bar, blah, bar, if you had properly
localized $foo inside the subroutine:

#!/usr/bin/perl

$foo = 'bar';
warn $foo;
baz();
warn $foo;

sub baz
{
  local $foo = $foo;
  warn $foo;
  $foo = 'blah';
  warn $foo;
}


Ronald