in reply to Re: whats wrong with this code?
in thread whats wrong with this code?

  doesn't do what you want anyway

I know while instead of foreach can do what I want but just wanted to know whats the problem with foreach?

Replies are listed 'Best First'.
Re^3: whats wrong with this code? (foreach internals)
by LanX (Saint) on Jan 18, 2017 at 12:59 UTC
    > wanted to know whats the problem with foreach?

    most probably is foreach internally holding an index to iterate the array.

    So it must terminate when the 6th element ( $array[5] ) is requested, because the array is already smaller then.

    look at this as demonstration

    use strict; use warnings; my @array= 1..10; my $idx=0; for my $elem (@array) { print "<\$array[$idx] == $elem> @array\n"; shift @array; $idx++ }

    out:

    <$array[0] == 1> 1 2 3 4 5 6 7 8 9 10 <$array[1] == 3> 2 3 4 5 6 7 8 9 10 <$array[2] == 5> 3 4 5 6 7 8 9 10 <$array[3] == 7> 4 5 6 7 8 9 10 <$array[4] == 9> 5 6 7 8 9 10

    This should be clearer, HTH!

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!