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

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
  • Comment on Re: I need a simple explantion of the difference between my() and local()
  • Download Code

Replies are listed 'Best First'.
Re: I need a simple explantion of the difference between my() and local()
by Dominus (Parson) on May 03, 2001 at 19:22 UTC
    Says ctl:
    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
    That's not the right example either, because you don't need local at all in that case:

    sub A { $x = 3; &B; } sub B{ $x } my $x = 2; print &A;
    It still prints 3 and not 2. And nobody who understands what my is about could expect it to print 2.

    weren't you a bit harsh to the previous poster as they made a simple mistake about where they put a line?
    I was harsh, and I apologize. I get very steamed when people post corrections that include broken code, but that's no excuse for being rude.
    it's also good to not give the original poster the impression that local() is a bug which should be gotten rid of
    Well, here we disagree. I think that's a fine impression to give them. The fraction of correct uses of local by beginning programmers is vanishingly small or zero.

    --
    Mark Dominus
    Perl Paraphernalia