![]() |
|
Welcome to the Monastery | |
PerlMonks |
comment on |
( #3333=superdoc: print w/replies, xml ) | Need Help?? |
local (the keyword) has NOTHING to do with local variables. In Perl, you use my (the keyword) to declare local (i.e., lexically scoped, or 'lexical') variables. The keyword local localizes a variable, whether it's named or anonymous or global (i.e., package variables, which are in the symbol table). To localize a variable is to stash away its value in such a way that exiting the enclosing scope will result in its being restored. For example:
One example of its use is with the Perl global, $/. Often, (in a subroutine, for example) it is necessary to set $/ = undef;, but to do so may break code which assumes its default value.
Hopefully, this explains WHEN to use local. Update: Whoops! I stand corrected (thanks, shotgunefx)! Starting with Perl 5.5, it became possible to localize arbitrary anonymous variables (e.g., local $obj->get_handle()->{some_property}->get_param("param1");). I never actually had a use for (and therefore never tried) localize a lexical; I suppose I just assumed that they could. Apologies to all for suggesting that localizing a lexical was possible. dmm If you GIVE a man a fish you feed him for a dayBut, TEACH him to fish and you feed him for a lifetime In reply to Re(4) Whether to use local()
by dmmiller2k
|
|