Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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

( #54115=categorized answer: print w/ replies, xml ) Need Help??

Q&A > subroutines > What is the difference between 'local' and 'my'? 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
-kel

Comment on Answer: What is the difference between 'local' and 'my'?
Select or Download Code
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?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2014-09-21 09:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (168 votes), past polls