Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

I need a simple explantion of the difference between my() and local()

by Jemts (Monk)
on May 02, 2001 at 20:12 UTC ( [id://77388]=perlquestion: print w/replies, xml ) Need Help??

Jemts has asked for the wisdom of the Perl Monks concerning the following question:

I have read all the tutorials at his site but they seem to complicate things more. Can someone please point out the differences between the two and when each should be used? Thanks
Jemts

Replies are listed 'Best First'.
Re: I need a simple explantion of the difference between my() and local()
by Dominus (Parson) on May 02, 2001 at 20:16 UTC
    No problem. my creates a private variable. The variable is only available inside the block in which you declared it. local does not; it gives a temporary value to a global variable, which is available anywhere in the program.

    and when each should be used?
    That's easy: Always use my, and never use local.

    Further reading.

    --
    Mark Dominus
    Perl Paraphernalia

      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)];
        Says Rhandom:
        my $x = 2; sub A { local $x = 3; &B; } sub B{ $x } print &A; #prints 3 not 2
        No, it doesn't do that. Too bad you didn't try it!

        "Always use my, never use local" is advice for people who don't understand the complexities yet. It's like the rule your mom told you about not talking to strangers. Is it always wrong to talk to strangers? No, of course not. Can a little kid be trusted to know when the rule doesn't apply? No.

        So until Jemts can read those tutorials and understand what they mean, he's better off following the rule. You might be better off also---it would at least stop you from saying silly things on Perlmonks.

        --
        Mark Dominus
        Perl Paraphernalia

        and when each should be used?
        That's easy: Always use my, and never use local.

      Given Ovid's recent diatribe on questioning authority, I am going to call you on this one. I understand your wanting to make a simple answer here, but there is a slightly less simple but infinitely more valuable way to put this. "Always use my unless you are localizing a perl internal variable, such as one from perldoc perlvar." I think newbies will understand that they are not localizing a perl variable, and probably will glaze over it if it isnt applicable. To those whom it is applicable, they will understand right away that at the least they need to do something different, and hopefully ask a question.

      For further clarity, I'd like to point out merlyn's excellent catch here, Re: Re: Re: Optimization for readability and speed (discussion), wherein he caught me messing about with $" when I should have been using local but wasnt. The node is in a simple context that I think most perl hackers can understand, even something-above-brand-new-newbies-to-perl'ers.

      yours in perl
      brother dep.

      --
      Laziness, Impatience, Hubris, and Generosity.

        Do you think that localizing special variables is something that needs to be encouraged in Perl beginners?

        Just to be clear, if you are going to change them, you should definitely localize them. If you are unclear on what I mean, read the very response of merlyn's that you are waving around.

        When you are done that question, do you think it is good to lie to people and say that the only legitimate reason for calling local is to modify special variables?

        In general I am with Dominus. Unless your knowledge level is to the point where you understand why you don't have any real choice but to call local, you should try to figure out how to solve your problem while calling my.

Re: I need a simple explantion of the difference between my() and local()
by stephen (Priest) on May 02, 2001 at 20:23 UTC
    The reason you're having a hard time finding a simple explanation of the differences between my and local is that the differences between my and local aren't simple.

    That said, you should almost always use 'my'. Use 'my' when you want to create a new variable inside a subroutine that nobody else can see:

    sub foo { my ($arg) = @_; my $bar = $arg + 1; return $bar; }

    'local' is mostly left over from Perl 4. Instead of creating a whole new variable, it takes an existing variable and saves a copy of its value that will be restored when you're done with it. There are only comparatively rare occasions where it is necessary to use 'local' instead of 'my'. Generally, in those cases, the compiler will scream at you if you try to use 'my' there, so as you're starting out, just use 'my'.

    stephen

Re: I need a simple explantion of the difference between my() and local()
by mothra (Hermit) on May 02, 2001 at 21:18 UTC
    From perldoc perlfaq7:
    What's the difference between dynamic and lexical (static) scoping? Between local() and my()?

    local($x) saves away the old value of the global variable $x, and assigns a new value for the duration of the subroutine, which is visible in other functions called from that subroutine.

    ...

    my($x) creates a new variable that is only visible in the current subroutine.

      if you use my() inside an if .. else conditional, it is also only visible in that scope.

      There is quite thorough documentation in perlman:perlsub

      $code or die
      $ perldoc perldoc
Re: I need a simple explantion of the difference between my() and local()
by wardk (Deacon) on May 02, 2001 at 22:07 UTC
        Au contraire.

        It is an extremely useful article. Among other things it explains very clearly why many things that people think they have to use local for don't need it after all. It is therefore useful as a way of explaining to people who are mistakenly using local.

        I consider this valuable.

      perhaps you are correct, the article ends with the following...

      Even the useful uses for local are mostly not very useful.

      Nobody should read it.

      it's on the web, so every one reading is likely nobody, eh? ;-)

      Update: ok, I get it...

Scope Difference
by tedv (Pilgrim) on May 02, 2001 at 21:21 UTC
    The difference between my and local is just one of scope. All subroutines called from the context of a local variable can access that variable, but not the my variable:
    sub foo { local $a = 10; my $b = 20; bar(); } sub bar { print "A: $a\n"; # Just fine print "B: $b\n"; # Warning from -w }

    If a piece of code needs to use local in this way, it's could probably be rewritten in a cleaner way. If my works, you should definitly use it.

    I won't condemn all use of local, however. I believe there are situations where you need to use local for dynamically generated anonymous functions, perhaps for use with $SIG{XYZ}. Can anyone confirm or deny this? I just remember writing signal code once where I needed to use local. (Of course, this is before I learned about the signal handling packages at CPAN.)

    -Ted

      A good use of local is when you are tweaking a special variable.

      Let's say you want to slurp a whole file into a scalar. Your code would look something like this:

      my $file; { local $/; open (FILE, "<$foo") or die "Unable to open $foo: $!"; $file = <FILE>; close FILE; }

      By enclosing the modification of $/ in a block, you avoid surprises down the road. $/ only has its value changed within that block.


      TGI says moo

        By narrowing the block that holds the local, you can further contain the effect.
        open(FILE, "<$foo") or die "$foo: $!"; my $file = do { local $/; <FILE> }; close(FILE);
Re: I need a simple explantion of the difference between my() and local()
by t'mo (Pilgrim) on May 03, 2001 at 06:52 UTC

    I know this is getting to be a long thread, but...

    Several of the answers in this thread, especially the reply offered by a, helped me to understand. It was the comment about how local pushes a new copy of the variable on a stack that is then popped when the scope is exited that helped me "see the light".

      Thanks guys you really helped me understand this topic alot better. This was my first post at this site, and i was supprised to see the response I got immedeatly. Thanks alot i know understand ( though not fully) what the difference is. Thanks alot

      Jemts

      "If you're traveling in a time machine, and you're eating corn on the cob, I don't think it's going to affect things one way or the other. But here's the point I'm trying to make: Corn on the cob is good, isn't it."

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://77388]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-03-29 14:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found