The next command, like redo and last, is used to subvert the block structure of a loop. Specifically, it causes execution immediately to skip the rest of the current iteration of the loop and continue with the next iteration (in this respect, it is like continue in C). A continue block, if one is attached to the loop, will therefore be executed.

The form next LABEL does the same, but for the loop with the LABEL.


Eratosthenes' sieve is

my @prime = (1) x $n;
for my $factor (2..sqrt($n)) {
  next unless $prime[$factor];    # ***
  for my $div (2..$n/$factor) {
    $prime[$div*$factor] = 0;
The point here is not efficiency, but a real-life use of next. The line marked "# ***" avoids running on non-prime factors; their multiples have already been eliminated.


The command NEXT {wa,i}s used to terminate a FOR loop. Thus,

10 FOR I=1 TO 100
is a good way to cheat in kindergarten.

The loop variable may be appended to the command (see above, "NEXT I"). The interpreter {c,w}ould use this to check your program (specifically, that the variable matched that of the FOR command, and that you had nested your loops correctly). BUT... If you "forgot" it (or left it out intentionally), the innermost loop would be closed. Paradoxically, this was faster on old interpreters (because they didn't need to perform the extra text, or even read the longer form from memory!). Generations of young 1970s/1980s programmers learned that correctness is the enemy of speed in this unfortunate way.

You could close multiple FOR loops by saying e.g. "NEXT K,J,I". This would close the loops indexed by the variables K,J,I, in that order:

10 FOR I=0 TO 9
20 FOR J=0 TO 9
30 FOR K=0 TO 9
Note that you still need to close the innermost loop first; "NEXT I,J,K" would fail miserably.

You could still omit the index variables from the statement. "NEXT,," would have had the same effect above (and would have been faster, to boot).