local is global for awhile

local gives a value to a global variable.
While the localization is in effect the original value
is unavailable. When it ends the old value is restored.

Update: Value is the wrong word above. The technical
term is thingie. local attaches the name to another
thingie for a while

my creates a new variable which may incidentally
have the same name as a global variable. This is the common
type of declaration as in C or C++.

Usually you want to use my.

You can't my %hash; local %hash; but
it is possible to my %hash; local $hash{key} = 1000;
I haven't used or examined this usage though.

I don't, GASP, have perl on this machine, so this is untested, but will demonstrate the important differences
between lexical and dynamic scoping.

$var =1; { my $var = 2; print "\$main::var >$main::var<\n"; print "\$var >$var<\n"; &show_var; # my var doesn't exist outside this scope } { local $var = 3; # local var gives $main::var a temporary value print "\$main::var >$main::var<\n"; print "\$var >$var<\n"; &show_var; # local var ceases to exist when we _leave_ this scope } print "\$var >$var<\n"; sub showvar { print "showvar($var)\n"; }

In reply to Re: nuances of my, and maybe local by rir
in thread nuances of my, and maybe local by Helter

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.