I don't use local() very often -- My programming style avoids global variables when I can -- so I might not understand all the subtleties of it.

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:

$foo = 'foo'; sub printfoo { print $foo; } printfoo(); # prints 'foo' { local $foo = 'bar'; printfoo(); # prints 'bar' } printfoo(); # prints 'foo'
is roughly equivilant to:
$foo = 'foo'; sub printfoo { print $foo; } printfoo(); #prints 'foo' { my $hidden_foo = $foo; $foo = 'bar'; &printfoo(); #prints 'bar' $foo = $hidden_foo; } 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).

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.