Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Answer: What is the difference between 'local' and 'my'?

by dsb (Chaplain)
on Jan 25, 2001 at 00:30 UTC ( #54115=categorized answer: print w/replies, xml ) Need Help??

Q&A > subroutines > What is the difference between 'local' and 'my'? - Answer contributed by dsb

When you use 'local' in to localize a variable, what is really happening is that Perl will store the value of any variable that already has the localized variables name when the localized variable is initialized. When the sub-routine ends and the program returns to the main body, Perl will restore the old value of the original variable. Ex:
$a = "one"; print $a, "\n"; routine(); print $a, "\n"; sub routine { local $a = "two"; print $a, "\n"; }
The output from this program would be:
one two one

Replies are listed 'Best First'.
Re: Answer: What is the difference between 'local' and 'my'?
by goldclaw (Scribe) on Jan 25, 2001 at 01:38 UTC
    And the output would be exacly the same if you used my. Check the article mentioned above for an explanation on the difference. Doesnt make much sense thoug. The only real use for local as I see it is this:
    1. You have a subroutine which calls a few others, perhaps in someone else's code(a module perhaps).
    2. Now, you need to change a global variable( turn of warning for pre-5.6.0 perl or perhaps turn of buffered output).
    3. You dont want to remember to switch it back to what it was when you return from your routine. This is feasable if you do some error checking on all your calls, and want to return as soon as one of them fails somehow.
    Solution: use local on the global variable, and set it to what you want. All the routines you call see the new value of this variable, and as soon as you return it is automagically reset to what it was.

    If you had used my instead, only your routine would have seen the change. Any routine you called, would still have seen the old value, since my is lexically scoped. GoldClaw

Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2017-07-28 17:45 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (432 votes). Check out past polls.