Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

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
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2018-01-23 23:06 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (254 votes). Check out past polls.