Private Variables via my()
Synopsis:
my $foo; # declare $foo lexically local
my (@wid, %get); # declare list of variables local
my $foo = "flurp"; # declare $foo lexical, and init it
my @oof = @bar; # declare @oof lexical, and init it
A "my" declares the listed variables to be confined
(lexically) to the enclosing block, conditional
(if/unless/elsif/else), loop
(for/foreach/while/until/continue), subroutine, eval, or
do/require/use'd file. If more than one value is listed,
the list must be placed in parentheses. All listed elements
must be legal lvalues. Only alphanumeric identifiers may be
lexically scoped--magical builtins like $/ must currently be
localized with "local" instead.
Unlike dynamic variables created by the "local" statement,
lexical variables declared with "my" are totally hidden from
the outside world, including any called subroutines (even if
it's the same subroutine called from itself or elsewhere--
every call gets its own copy).
====================
Temporary Values via local()
NOTE: In general, you should be using "my" instead of
"local", because it's faster and safer. Exceptions to this
include the global punctuation variables, filehandles and
formats, and direct manipulation of the Perl symbol table
itself. Format variables often use "local" though, as do
other variables whose current value must be visible to
called subroutines.
Synopsis:
local $foo; # declare $foo dynamically local
local (@wid, %get); # declare list of variables local
local $foo = "flurp"; # declare $foo dynamic, and init it
local @oof = @bar; # declare @oof dynamic, and init it
local *FH; # localize $FH, @FH, %FH, &FH ...
local *merlyn = *randal; # now $merlyn is really $randal, plus
# @merlyn is really @randal, etc
local *merlyn = 'randal'; # SAME THING: promote 'randal' to *randal
local *merlyn = \$randal; # just alias $merlyn, not @merlyn etc
A local() modifies its listed variables to be local to the
enclosing block, (or subroutine, eval{}, or do) and any
called from within that block. A local() just gives
temporary values to global (meaning package) variables.
This is known as dynamic scoping. Lexical scoping is done
with "my", which works more like C's auto declarations.