local() vs my()

Dominic Mitchell dom at happygiraffe.net
Wed Feb 22 11:29:46 GMT 2006

On Wed, Feb 22, 2006 at 11:00:57AM +0000, Peter Hickman wrote:
> O'Shaughnessy, Jamie wrote:
> >You seem to get a lot of people that have done what may be some 
> >interesting web work, but it's very small scale and they only have 
> >experience of working in very small teams and often have very limited 
> >software engineering experience. I've found it only too common that their 
> >perl knowledge is "user level" at best - ask them to explain the 
> >difference between my and local and they may just muddle through, start 
> >talking about stashes, closures, etc and they're totally lost.
> A little worrisome this, I couldn't tell you the difference between
> local and my, I could probably muddle through our. I do know closures
> but what's a stash? I would like to think that I am at least competent
> after all these years but it sounds like I would probably fail.

The difference between local and my is well worth knowing.  And the
correct answer is "Don't use local unless you know what you're doing".

The true answer is that local is /dynamic/ in scope instead of
/lexical/.  So a variable declared with my is only visible to things in
the same set of braces (effectively).  Whereas something declared with
local is visible to not only everything in the current set of braces,
but everything that's called from there as well.

The other advantage of local is that it restores the variables previous
value when you leave that scope.  A common example[1] is:

  eval {
    local $SIG{__DIE__};
    # Do stuff that might blow up.

If a die handler is present, it will be switched off for the duration of
that scope, and everything that gets called from that scope.  And it
will be restored to its previous value after the eval{}.

MJD wrote some good articles on local.



[1] In our code, as we use mason, which installs one of the blasted
things.  Don't use die handlers, kids!

More information about the london.pm mailing list