Behaviour of next in the for Loop

Contents | Up | Prev | Next

# 1.1. Behaviour of next in the for Loop

An important difference between the `for` loop and the `while` loop is the behaviour of `next` inside it. In a `for` loop, `next` skips the rest of the iteration but still executes the iteration commands which were passed to the loop as arguments.

For example, the following program prints the first 200 primes:

    MAIN_LOOP: for(
        @primes=(2), $i=3 ;
        scalar(@primes) < 200 ;
        $i++
        )
    {
        foreach $p (@primes)
        {
            if ($i % $p == 0)
            {
                next MAIN_LOOP;
            }
        }

        push @primes, $i;
    }

    print join(", " , @primes), "\n";

Now, the equivalent program using a while loop:

    @primes = (2);
    $i = 3;
    MAIN_LOOP:
    while (scalar(@primes) < 200)
    {
        foreach $p (@primes)
        {
            if ($i % $p == 0)
            {
                next MAIN_LOOP;
            }
        }

        push @primes, $i;
        $i++;
    }

    print join(", " , @primes), "\n";

gets stuck. (why?)

Contents | Up | Prev | Next