Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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

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

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

The difference is between dynamic and static scope. 'my' behaves as the auto variables of C/C++ and most other languages. 'local', on the other way, behaves as bind variables in Lisp. The real difference can be seen when you have several scopes.

Suppose you have the following code:

our $a = 3; sub f { print "$a\n"; } sub g { my $a = 7; print "$a\n"; &f (); print "$a\n"; } &g (); print "$a\n";
you would get: 7 - 3 - 7 - 3

If you substitute the my in 'g' by local, you get: 7 - 7 - 7 - 3

Internally, the difference in the implementation is that local stores the variable value in a stack for the duration of the scope, and restores it at the end of the scope, while my actually creates a new variable which hides the outer one for the duration of the scope where it is defined, but not for other scopes which may be invoked. creates

Comment on Answer: What is the difference between 'local' and 'my'?
Download Code
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 perusing the Monastery: (9)
As of 2014-12-17 23:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (40 votes), past polls