Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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

by fpina (Pilgrim)
on Apr 04, 2001 at 03:33 UTC ( #69508=categorized answer: print w/replies, xml ) Need Help??

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

Log In?

What's my password?
Create A New User
[ovedpo15]: its easy with three "if"s or one long "if" but is there a "nice" way :)

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2018-04-22 13:16 GMT
Find Nodes?
    Voting Booth?