3. Declaring Local Variables with "my"

Variables can be made local to their own scope by declaring them using a keyword called my. When the interpreter leaves the scope, the variable will be restored to its original value.

Here's an example:

$a = 5;
$b = 1000;
{
    my ($b);
    for($b=0;$b<10;$b++)
    {
        print $a, "*", $b, " = ", ($a*$b), "\n";
    }
}

print "Now, \$b is ", $b, "\n";

If you wish to declare more than one variable as local you should use a set of parenthesis surrounding the variable list. For example: my (@array, $scalar1, %hash, $scalar2);. If you want to declare only one variable, then they are optional.


Written by Shlomi Fish