For loop in perl

my @array=(1..10); for my $i (@array){$i++;} print "array is now:@array"; 

this is a change in array values. Why?

+2
source share
4 answers

This is what is defined by the for statement in Perl. See the documentation for cycle loops in man perlsyn :

If any LIST element is an lvalue, you can change it by changing the VAR inside the loop. Conversely, if any LIST element is not an lval value, any attempt to change this element will fail. In other words, the foreach loop index index is an implicit alias for each item in the list that you are looping.

+6
source

This is documented behavior. See perldoc perlsyn :

The foreach loop iterates over the normal value of the list and sets the VAR variable - each element in turn.

If any LIST element is an lvalue, you can change it by changing the VAR inside the loop. Conversely, if there is a LIST element that is not an lvalue value, any attempt to change this element will fail. In other words, the foreach loop index variable is an implicit alias for every element in the list that you are looping about.

+3
source

The loop variable $i smoothed over each element of the array in turn.

This means that if you change $i , you change the array.

+1
source

I believe this is due to the fact that in perl, when you iterate over an array, each element is passed by reference, which means that when $ i changes in a loop, it changes the actual value in the array. I am not sure how to do this at the expense of cost.

0
source

All Articles