10.13.3.3. Using local( ) on parts of aggregates
The third situation is exceedingly rare, except for one common case.
Because the local operator is really a "save value" operator, you can
use it to save off just one element of an array or hash, even if that
array or hash is itself a lexical!
my @nums = (0 .. 5);
sub first {
local $nums[3] = 3.14159;
second( );
}
sub second {
print "@nums\n";
}
second( );
0 1 2 3 4 5
first( );
0 1 2 3.14159 4 5
The only common use for this kind of thing is for temporary signal
handlers.
sub first {
local $SIG{INT} = 'IGNORE';
second( );
}
Now while second is running, interrupt signals are
ignored. When first returns, the previous value of
$SIG{INT} is automatically restored.
Although a lot of old code uses local, it's
definitely something to steer clear of when it can be avoided.
Because local still manipulates the values of
global variables, not local variables, you'll run afoul of
use strict unless you declared
the globals using our or the older
use vars.
With dynamic scoping, a variable is accessible if it's found in the
current scope—or in the scope of any frames (blocks) in its
entire subroutine call stack, as determined at runtime. Any functions
called have full access to dynamic variables, because they're still
globals, just ones with temporary values. Only lexical variables are
safe from such tampering.
Old code that says:
sub func {
local($x, $y) = @_;
#....
}
can almost always be replaced without ill effect by the following:
sub func {
my($x, $y) = @_;
#....
}
The only case where code can't be so upgraded is when it relies on
dynamic scoping. That would happen if one function called another,
and the latter relied upon access to the former's temporary versions
of the global variables $x and
$y. Code that handles global variables and expects
strange action at a distance instead of using proper parameters is
fragile at best. Good programmers avoid this kind of thing like the
plague. (The solution is to explicitly pass values as parameters,
rather than storing them in shared global variables.)