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

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?

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (12)
As of 2016-05-06 17:05 GMT
Find Nodes?
    Voting Booth?