I have just begun to learn Perl and found myself stymied by the result of the following block of code:
@x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach (@x) {
$x = pop (@x) ;
$y = shift (@x);
print ("$x $y \n");
}
The output is:
10 1
9 2
8 3
7 4
I had expected another line: 6 5
. Why is there not such a line? Is it because after the iteration that prints 7 4
, the number of elements left in the array is equal to the number of iterations already completed, and so as far as Perl is concerned, the loop is done?
A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range.
There is no difference. From perldoc perlsyn: The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.
C# provides an easy to use and more readable alternative to for loop, the foreach loop when working with arrays and collections to iterate through the items of arrays/collections. The foreach loop iterates through each item, hence called foreach loop.
You probably shouldn't modify the list during iteration. From perldoc perlsyn
:
If any part of
LIST
is an array,foreach
will get very confused if you add or remove elements within the loop body, for example withsplice
. So don't do that.
If you print out $_
during the loop (print ("$x $y $_\n");
), you can see what's going on:
10 1 1
9 2 3
8 3 5
7 4 7
In this case Perl is just maintaining an index that it increments through the array. Since you delete the elements from the start, the index falls off the end of the modified array at the end of the fourth iteration, and so the foreach
loop terminates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With