"Perl for Perl Newbies" - Part 2Declaring Local Variables with "my"

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:

$x =
5;
$y =
1000;
{

my (
$y);

for(
$y=
0;
$y<
10;
$y++)
    {

print
$x,
"*",
$y,
" = ", (
$x*
$y),
"
\n
";
    }
}

print
"Now, 
\$
y is ",
$y,
"
\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