My understanding of local() is that it takes the current value of the global variable being local()ed and stores it in a hidden lexical variable, with the added semantics that the hidden lexical variable has a destrictor that restores the original value.
In otherwords:
is roughly equivilant to:$foo = 'foo'; sub printfoo { print $foo; } printfoo(); # prints 'foo' { local $foo = 'bar'; printfoo(); # prints 'bar' } printfoo(); # prints 'foo'
with the additional caveat that the $foo = $hidden_foo is always executed, regardless of how the block exits. It's effectively a destructor on $hidden_foo (which, being lexical and not being available to take references of, is destroyed when the block exits).$foo = 'foo'; sub printfoo { print $foo; } printfoo(); #prints 'foo' { my $hidden_foo = $foo; $foo = 'bar'; &printfoo(); #prints 'bar' $foo = $hidden_foo; } printfoo() #prints 'foo'
This masking of the original value allows you to do lots of things with $foo that you couldn't necessarily do without tromping over the original value, and messing things up for the rest of the program outside of the scope of the local().
When I posted a query like this on the perl6-language list, I got replies telling me I had missed some subtleties -- usually that the re-valuing of $foo affected dynamic sub calls within the dynamic scope of the local(). I don't think I missed that subtlety, unless there is more to it than I demonstrated above.
Am I missing anything? Are there any subtleties I don't quite get?
In reply to YAlQ: Yet Another local() Question. by BlaisePascal
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |