Always put the for loop iterator variables as 'my' inside the for loop.
foreach my $region (@regions) {
# something happening in the loop
}
If you write
my $region
foreach $region (@regions) {
# something happening in the loop
}
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
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";
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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|