O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.6. Semiprivate Variables Using local

Perl gives you a second way to create "private" variables, using the local function. It is important to 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 you may eventually need to know that local variables are really global variables in disguise. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required