learning Perl - the "shift" function stops half way through

Spungo

Diamond Member
Jul 22, 2012
3,217
2
81
nevermind figured it out. sorry!




I might as well say what I was doing and what was wrong.

Code:
foreach (@array) {
   $number = shift @array;
   .....stuff....
}

It'll stop half way through because it's shortening the array each time it loops.
 
Last edited:

MrDudeMan

Lifer
Jan 15, 2001
15,069
94
91
In case you're interested in other syntactic-sugar, these solutions would have also worked:

Code:
foreach (@array) { #could also be 'for' instead of 'foreach'
    print;   # uses the built-in variable '$_'
}

Code:
foreach $x (@array) {
    print $x;
}

If you need an index:

Code:
foreach $i (0 .. $#array) {
    print @array[$i];
}

Code:
for($i = 0; $i < @array; $i++) {
    print @array[$i];
}

There are advantages and disadvantages to each approach.