note
scooper
Always put the for loop iterator variables as 'my' inside the for loop.
<code>
foreach my $region (@regions) {
# something happening in the loop
}
</code>
If you write
<code>
my $region
foreach $region (@regions) {
# something happening in the loop
}
</code>
Perl silently declares a new lexical variable (also named $region) as the
iterator variable. The new $region is scoped to the loop block and hides
any variable $region from the outer scope.
By explicitly putting the my in the foreach, you're reminding
yourself of this behaviour. You're avoiding the
misconception that the last value of $region will be available after
the for loop (it won't, however you try to scope it). If you want that
information you have to save it to an outside variable inside the loop
<code>
my $latest_region;
foreach my $region (@regions) {
$latest_region = $region;
# something happening in the loop
last if (some condition);
}
print "last region considered was $latest_region\n";
</code>
Most of this information lifted from "Non-Lexical Loop Iterators",
'Always declare a for loop iterator variable with my', in
"Perl Best Practices", by Damian Conway
591922
591922