perl

How to jump to specific point of a foreach iteration?


this is a minimal working example of how to skip iterations within a list of numbers:

#!/usr/bin/env perl

use strict;
use feature 'say';
use warnings FATAL => 'all';
use autodie ':default';

foreach my $n (0..29) {
    if ($n % 4 == 0) {
        $n += 5; # goes to $n+1, even though I increased $n to $n+5
        next;
    }
    say $n;
}

I cannot alter $n so that it jumps several iterations within the number.

That is, I want next to move 5 up, not 1.

How can I skip multiple iterations of a foreach loop?


Solution

  • You could use a while loop. One that takes the shape of "C-style for loop" is particularly apt.

    Keep in mind that next will execute the third clause of the "C-style for loop" before rechecking the condition and re-entering the loop, so you will need to place the incrementing into the loop body or use $n += 4; to avoid incrementing by 6.

    for ( my $n = 0; $n <= 29; ) {
       if ( $n % 4 == 0 ) {
          $n += 5;
          next;
       }
    
       say $n;
       ++$n;
    }
    
    for ( my $n = 0; $n <= 29; ) {
       if ( $n % 4 == 0 ) {
          $n += 5;
       } else {
          say $n;
          ++$n;
       }
    }