Perl gives you a second way to create private variables, using the local
function. You must, however, understand the differences between my
and local
. For example:
$value = "original";
tellme();
spoof();
tellme();
sub spoof {
local ($value) = "temporary";
tellme();
}
sub tellme {
print "Current value is $value\n";
}
This prints out:
Current value is original
Current value is temporary
Current value is original
If my
had been used instead of local
, the private reading of $value
would be available only within the spoof()
subroutine. But with local
, as the output shows, the private value is not quite so private; it is also available within any subroutines called from spoof()
. The general rule is that local
variables are visible to functions called from within the block in which those variables are declared.
Whereas my
can be used only to declare simple scalar, array, or hash variables with alphanumeric names, local
suffers no such restrictions. Also, Perl's built-in variables such as $_
, $1
, and @ARGV
, cannot be declared with my
, but work fine with local
. Because $_ is so often used throughout most Perl programs, it's probably prudent to place a
local $_;
at the top of any function that uses $_
for its own purposes. This assures that the previous value will be preserved and automatically restored when the function exits.
In your more advanced programming efforts, you may eventually need to know that local
variables are really global variables in disguise. That is, the value of the global variable is saved and temporarily replaced with the locally declared value.
By and large, you should prefer to use my
over local
because my
is faster and safer.