For the most part, that is true, you should always use "my". There are a few cases where local is better:
local *HANDLE; local $SIG{ALRM} = 'ignore'; my $x = 2; ################# UPDATE ####################### ## Without removing my mistake above, so that ## anybody reading this node will note how ## silly (see Dominus's generous -cough- reply) ## I was (and I was silly to post code that I ## would never actually use and hadn't tested ## in a negative response to an almost saintly monk). ## ## The reason the code failed is because ## I need to do something like: ## use vars qw($x); ## OR ## $main::x; ## Otherwise, local will fail (as per ctl's reponse) ## because it doesn't have access to "my"ed variables. ## It won't fail on the grounds that you shouldn't use ## local. ## ## Dominus didn't answer the response. ## There are still times when you need to use local ## (and saying only use IO::Handle or Symbol::gensym() or ## don't use SIG's is not an appropriate answer -- ## sometimes we have no choice but to use FILEHANDLES ## and SIG's) ## ## Meanwhile maybe I should post a meditation about ## answering with answers and not predispositions. ################# UPDATE ####################### sub A { local $x = 3; &B; } sub B{ $x } print &A; #prints 3 not 2


So, unless you need something like the above (and understand why), you really should use "my" (or fully qualify the variable). my @a=qw(random brilliant braindead); print $a[rand(@a)];

In reply to Re: Re: I need a simple explantion of the difference between my() and local() by Rhandom
in thread I need a simple explantion of the difference between my() and local() by Jemts

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.