{
my $x;
}
This means that the scalar variable $x can't be accessed outside of the braces. However, this is also valid Perl:
{
local $x;
}
Perversely, this does not create a local variable named $x. This actually does this:
- save the current value of $x (outside the braces) somewhere safe.
- make a new variable named $x that can be used inside of $x.
- when the scope of the new variable is cleared, replace $x with the old value.
This is a little complicated, so here's an example that illustrates the behavior of local:
$x = 3;
{
local $x = 'foo';
print $x, "\n";
}
print $x, "\n";
The output of this program is:
foo
3
In general, you should use my much more frequently than local, and overuse of
local can be considered a code smell. Read more about my and local in Coping with Scoping.