Wow. I just found a pretty weird behavior on the part of foreach.
It looks like Perl doesn't reset the iterator if you exit the loop
via last, so that a future entrance into the loop will start you iterating
through your array at the same place as you left off, which means that
you will quickly fall off the end of your array and start getting $_
equal to undef. Here is a code snippet that demonstrates the problem,
from a very silly quickie I wrote to look up CNAMEs on a misconfigured DNS
where host(1) was not working properly...
my $domain_file;
FILE: foreach (@domain_files)
{
$domain_file = $_;
print "\tLooking in domain file $domain_file\n" if (DEBUG == 2);
open DOMAIN_FILE, $domain_file
or die "Could not open domain file $domain_file: $!";
while () #! Could use globbing here...
{
if (m/$aname_regex/)
{
$aname = $1;
print "\tFound A name: $aname in file $domain_file\n" if
DEBUG;
#There's only one A name for a given host, so
#stop checking files...
last FILE; #*Trouble! foreach iterator is not reset.
}
}
}
It just so happens that this loop appears inside a subroutine I call
a bunch of times. Even between subroutine calls, the iterator for
@domain_files is not reset! In short, @domain_files is screwed up.
This seems like a pretty serious bug to me. Is this a known shortcoming
of Perl? The work-around is to use a for loop with your own iterator:
FILE: for (my $i = 0; $i <= $#domain_files; $i++)
{
$domain_file = @domain_files[$i];
print "\tLooking in domain file $domain_file\n" if (DEBUG == 2);
open DOMAIN_FILE, $domain_file
or die "Could not open domain file $domain_file: $!";
while () #! Could use globbing here...
{
if (m/$aname_regex/)
{
$aname = $1;
print "\tFound A name: $aname in file $domain_file\n" if
+DEBUG;
last FILE;
}
}
}
Thanks for any comments you can provide on this. It's a weird one...
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.