Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of 'foreach' in Perl

Tags:

foreach

perl

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?

like image 449
verbose Avatar asked Oct 17 '12 05:10

verbose


People also ask

What does foreach do in Perl?

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.

What is the difference between for and foreach in Perl?

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.

What is foreach loop with example?

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.


1 Answers

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 with splice. 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.

like image 88
nneonneo Avatar answered Sep 30 '22 14:09

nneonneo