Search code examples
perlloops

Perl - difference between 'next' and 'continue'?


Quick Perl question: when going through a loop (say a while loop), what is the difference between a next and continue command? I thought both just skip to the next iteration of the loop.


Solution

  • The continue keyword can be used after the block of a loop. The code in the continue block is executed before the next iteration (before the loop condition is evaluated). It does not affect the control-flow.

    my $i = 0;
    when (1) {
      print $i, "\n";
    }
    continue {
      if ($i < 10) {
        $i++;
      } else {
        last;
      }
    }
    

    Is almost equivalent to

    foreach my $i (0 .. 10){
      print $i, "\n";
    }
    

    The continue keyword has another meaning in the given-when construct, Perl's switch-case. After a when block is executed, Perl automatically breaks because most programs do that anyway. If you want to fall through to the next cases the continue has to be used. Here, continue modifies the control flow.

    given ("abc") {
      when (/z/) {
        print qq{Found a "z"\n};
        continue;
      }
      when (/a/) {
        print qq{Found a "a"\n};
        continue;
      }
      when (/b/) {
        print qq{Found a "b"\n};
        continue;
      }
    }
    

    Will print

    Found a "a"
    Found a "b"
    

    The next keyword is only available in loops and causes a new iteration incl. re-evaluation of the loop condition. redo jumps to the beginning of a loop block. The loop condition is not evaluated.