Friday, February 26, 2010

Local Variables in Perl

Many programming languages allow you to associate variables with a scope. The scope of a variable defines the context in which a variable can be accessed and manipulated. In Perl, this is how you declare a local variable inside of a scope:

{
 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.