in reply to whats wrong with this code?

You're iterating over an array that you are modifying at the same time. This is not a recommended approach and doesn't do what you want anyway:

foreach(@array){ shift (@array);

Most likely you want to keep on going while the array @array is not empty. Using a while loop is better for that.

Replies are listed 'Best First'.
Re^2: whats wrong with this code?
by purnak (Acolyte) on Jan 18, 2017 at 09:03 UTC

      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?
      > 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!