local EXPR
In general, you should be using "my" instead of "local", because it's
faster and safer. Format variables often use "local" though, as
do other variables whose current value must be visible to called
subroutines. This is known as dynamic scoping. Lexical scoping is
done with "my", which works more like C's auto declarations.
A local modifies the listed variables to be local to the enclosing block,
subroutine, eval or "do". If more than one value is listed, the list
must be placed in parens. All the listed elements must be legal
lvalues. This operator works by saving the current values of those
variables in LIST on a hidden stack and restoring them upon exiting the
block, subroutine or eval. This means that called subroutines can also
reference the local variable, but not the global one. The LIST may be
assigned to if desired, which allows you to initialize your local
variables. (If no initializer is given for a particular variable, it
is created with an undefined value.) Commonly this is used to name the
parameters to a subroutine. Examples:
sub RANGEVAL {
local($min, $max, $thunk) = @_;
local $result = '';
local $i;
for ($i = $min; $i < $max; $i++) {
$result .= eval $thunk;
}
$result;
}
if ($sw eq '™v') {
local @ARGV = @ARGV;
unshift(@ARGV,'echo');
system @ARGV;
}
if ($base12) {
local(%digits) = (%digits,'t',10,'e',11);
parse_num();
}
Note that local() is a run™time command, and so gets executed every
time through a loop. In Perl 4 it used more stack storage each
time until the loop was exited. Perl 5 reclaims the space each time
through, but it's still more efficient to declare your variables
outside the loop.
A local is simply a modifier on an lvalue expression.
When you assign to a localized EXPR, the local doesn't change whether
EXPR is viewed as a scalar or an array. So
local($foo) = <STDIN>;
local @FOO = <STDIN>;
both supply a list context to the righthand side, while
local $foo = <STDIN>;
supplies a scalar context.
|
|
|