in reply to whats wrong with this code?

I would code it like this (no need for the print before the loop and also swap order of statements within the loop):
#!/usr/bin/perl use strict; use warnings; my @array=(1..10); while (@array) { print "@array\n"; shift (@array); } __END__ 1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 3 4 5 6 7 8 9 10 4 5 6 7 8 9 10 5 6 7 8 9 10 6 7 8 9 10 7 8 9 10 8 9 10 9 10 10
A for() or foreach() loop calculates some stuff before it starts looping that is not "re-calculated". That is both "good" and "bad". The while(cndx){} construct recalculates the cndx at each iteration.

Update: This may confuse more than it helps, but an attempt...
When you iterate over foreach(@array), the default variable $_ is being set to each element of @array. The shift mucks around with this progression.

#!/usr/bin/perl use strict; use warnings; my @array=(1..10); print "@array\n"; foreach (@array) { #shift (@array); #see below print "default var = $_ @array\n"; } __END__ 1 2 3 4 5 6 7 8 9 10 default var = 1 1 2 3 4 5 6 7 8 9 10 default var = 2 1 2 3 4 5 6 7 8 9 10 default var = 3 1 2 3 4 5 6 7 8 9 10 default var = 4 1 2 3 4 5 6 7 8 9 10 default var = 5 1 2 3 4 5 6 7 8 9 10 default var = 6 1 2 3 4 5 6 7 8 9 10 default var = 7 1 2 3 4 5 6 7 8 9 10 default var = 8 1 2 3 4 5 6 7 8 9 10 default var = 9 1 2 3 4 5 6 7 8 9 10 default var = 10 1 2 3 4 5 6 7 8 9 10 With the "shift turned on" (not commented out) 1 2 3 4 5 6 7 8 9 10 default var = 1 2 3 4 5 6 7 8 9 10 default var = 3 3 4 5 6 7 8 9 10 default var = 5 4 5 6 7 8 9 10 default var = 7 5 6 7 8 9 10 default var = 9 6 7 8 9 10

Replies are listed 'Best First'.
Re^2: whats wrong with this code?
by purnak (Acolyte) on Jan 18, 2017 at 11:14 UTC
    Thanks for the answer. I think Im now close to understanding what happens.
      Glad to hear that this is helping. I was worried about confusing things more.

      A few more comments about the difference between "while" and "foreach"..

      This while loop is testing whether or not there are any elements in @array. That number of elements is the scalar value of the array. The keyword scalar is not needed because in this context it is implied. However, "scalar" can be used. The while loop does not muck with the $_ variable. But the foreach loop does.

      while (scalar @array) #scalar not needed, but this is what is meant { print "@array\n"; shift (@array); }