Actually, all he has to do is:
sub A { local $x = 3; &B; } sub B{ $x } my $x = 2; print &A; #prints 3 not 2

And it does print 3 rather than 2. The order that he had it in would produce the error "Can't localize lexical variable $x at foo12.pl line 4." However, moving down, as I have done above, illustrates the point that the previous poster made.

As for the advice for newcomers to perl, I think that you're right. Using my() instead of local() in all cases until you've learned the intracacies is indeed good advice. However, weren't you a bit harsh to the previous poster as they made a simple mistake about where they put a line? While it's always good to provide good advice for a person's skill level, it's also good to not give the original poster the impression that local() is a bug which should be gotten rid of. Simply adding "until you understand the intricacies of local()" would suffice quite nicely to not risk turning the guy off to ever investigating local().


With humble thanks,
    -Chris
--
"They laughed at Einstein. They laughed at the Wright Brothers. But they also laughed at Bozo the Clown." -- Carl Sagan

In reply to Re: I need a simple explantion of the difference between my() and local() by ctl
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.