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

I want to use a foreach loop going through an array, but at the same time, i will be shifting elements from the array, and I want to reset the array number back to '0' otherwise I will be skipping every other element:
foreach my $No (@Nos){ push(@String, $Chains{$chain}{$No}) ; $prevNo = $No; shift(@Nos); print "@Nos\n"; }
the list in @Nos being (11,14,19...) i only get 11, 19, because whilst I've shifted a number, the loop's array indice is still 1, so it ignores 14, as 14 becomes [0].

any better way of doing this?
Thanks Sam

Replies are listed 'Best First'.
Re: resetting a loop
by jmcnamara (Monsignor) on Sep 10, 2002 at 15:24 UTC

    You could use a while loop instead of a for loop:
    #!/usr/bin/perl -w my @array = (11, 14, 19, 20); while (@array) { print "@array\n"; my $var = shift @array; }

    --
    John.

Re: resetting a loop
by seaver (Pilgrim) on Sep 10, 2002 at 15:19 UTC
    i reformatted the code, sorry if it's confusing
    foreach my $No (@Nos){ push(@String, $Chains{$chain}{$No}) ; $prevNo = $No; shift(@Nos); print "@Nos\n"; }