The
next operator stops the current iteration of the loop and begins the next one. It does not assign $i to $j again. Modifying the loop control variable ($i = 0) and saying
next creates an infinite loop. You can verify this by adding the following line as the first line of the loop:
print "I: $i\n";
Generally, loops like this are discouraged in Perl because there are better ways to do things. I might write your code like this:
my $pos = 0;
for ($j .. $#array) {
if ($array[$_] eq 'blah') {
$pos = $_;
last;
}
}
By the end of my snippet, $pos will either contain the appropriate index, or will still be 0. It's shorter and needs no labels. Best of all, it doesn't need $i, so the question is moot.
I hope this helps.
Update: HyperZonk suggests that the original poster may want to search the first half of the array if $j through the end didn't have the element. In that case, maybe the C-style loop is better:
my ($i, $end) = ($j, $#array);
my $pos = 0;
for (; $i <= $end; $i++) {
last if ($array[$i] eq 'blah');
if ($i == $#array) {
$i = 0;
$end = $j - 1;
}
}
Untested, but it's one way to do it.
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.