use strict;
my $i = 12;
print qq{Before the loop, \$i is $i\n};
for (my $i=0; $i<3; $i++) {
print qq{Within the loop, \$i is $i\n};
}
print qq{After the loop, \$i is $i\n};
This will print out
Before the loop, $i is 12 Within the loop, $i is 0 Within the loop, $i is 1 Within the loop, $i is 2 After the loop, $i is 12What happens here is that the variable $i declared within the for loop has a lifetime only within that loop, and doesn't affect any possible variable $i declared outside of the loop. This also means that this program
use strict;
for (my $i=0; $i<3; $i++) {
print qq{Within the loop, \$i is $i\n};
}
print qq{After the loop, \$i is $i\n};
will not run under use strict;, as the variable
$i used in the print statement after the loop
hasn't been declared within that scope.
While it might take some getting used to, variable scoping is a useful tool in debugging programs - although there are an effective infinite number of variable names one can use, we tend to use the same variable names for certian types of variables (for example, $i for an integer counting variable). Variable scoping can prevent a common error of using the same variable name in two places and assuming they're different. For example, consider
$i = 1986;
..... # 1200 lines later
for ($i=0; $i<4; $i++) {
......
}
..... # 4300 lines later
print qq{\$i is now $i};
In this example, $i is used in two places,
presumably for a year (1986) and for a counter in
the for loop. In the final print statement
we might be expecting $i to be the year, but
would be surprised to find it's value altered (through
the for loop). Localizing the variable $i
within the for loop would allow both variables
$i to exist independently within their appropriate
scopes.