Thursday, December 9, 2010

yet another perl limitation

Another funny thing about perl.
Suppose, $i is 4.


while ($i > 0) {
    $i--;

    next if ($i == 2);

    print $i, "\n";
}


will produce
3 1 0


which is quite expected result. So far, so good.

Moving to do-while

do {
    $i--;

    next if ($i == 2);

    print $i, "\n";
} while ($i > 0);


Oops, bad luck:
3
Can't "next" outside a loop block at ./test.pl line 10.

And at the same time
do {
    $i--;

    next if ($i == 2);

    print $i, "\n";
} for (1 .. $i);


will happy to write
3 1 0

Guess why?

perldoc will shed light:
do BLOCK does not count as a loop, so the loop control statements next, last, or redo cannot be used to leave or restart the block. See perlsyn for alternative strategies.

Well... dunno... Hope, they really had reasons to do so.

No comments:

Post a Comment