Loop Control

The next, last, and redo statements allow you to change the flow of control in the loop mid-stream, as it were. You can use these three statements in while loops, until loops, and for and foreach loops, but not in the do-until and do-while variants.

next

The next statement causes the rest of the loop to be skipped and control to pass back to the conditional test at the top. If there's a continue block, it is executed before control returns to the top of the loop.

  $done = 0;
  while (!$done) {
    $line = <STDIN>;
    chomp $line;
    next if $line eq 'SKIP';
    print $line,"\n";
  } continue {
    $done++ if $line eq 'END';
  } 

last

The last statement causes the loop to terminate prematurely, even if the loop conditional is still true:


  while ( $line = <STDIN> ) {
    chomp $line;
    last if $line eq 'END';
    print $line,"\n";
  }

redo

The redo statement is rarely used. It causes flow of control to jump to the top of the loop, like next. However, the continue block, if any, is not executed. In a for loop, the update expression is not executed.

  for (my $i=0; $i<10; $i++) {
    chomp ($line = <STDIN>);
    redo if $line eq 'SKIP'; # $i won't get incremented in this case
    print "Read line $i\n";  
  }

Nested Loops

If you have two or more nested loops, next, last and redo always apply to the innermost loop. You can change this by explicitly labeling the loop block and referring to the label in the loop control statement:

 XLOOP:
  for (my $x=0; $x<10; $x++) {
    for (my $y=0; $i<100; $y++) {
      next XLOOP unless $array[$x][$y] > 0;
      print "($x,$y) = $array[$x][$y]\n";
    }
  }


<< Previous
Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Thu Oct 12 22:08:17 EDT 2000