Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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

by dsb (Chaplain)
on Jan 25, 2001 at 00:30 UTC ( [id://54115]=note: print w/replies, xml ) Need Help??


in reply to What is the difference between 'local' and 'my'?

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

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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-04-19 14:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found