Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Esteemed Monks, I am an apprentice in Perl, using a Wintendo running ActiveState Perl 5.8.4. In the code below, the 'for'-loop bails out early, and finishes when the array has two more elements. However, if I exchange the 'for' for 'while' - everything works. Why?
#!/usr/bin/perl my @results = qw/item item item item item/; my $output = undef; for (@results) { print "the items are: @results\n"; print "text is: $output\n"; $text = shift @results; }

Replies are listed 'Best First'.
Re: 'For' loop bails out early?
by Fletch (Bishop) on May 31, 2007 at 15:02 UTC

    Because you're modifying the array you're iterating over which is a no-no. See perlsyn for the details, but the cliffs notes is use while if you're modifying the array in place just as you've discovered.

    Update: OK, it's not really extensive details; here's the warning in its entirety:

    If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.
      >>Fletch. Thank you very much! /Anonymous monk (Perl XP +1)