my @array=(1..10);
for my $i (@array){$i++;}
print \"array is now:@array\";
this is changing the values of the array. Why?
I believe it is because in perl when you loop through an array, each element is passed by reference, meaning when you change $i in the loop, it is changing the actual value in the array. I'm not sure how to make it pass by value, though.
This is documented behaviour. See perldoc perlsyn:
The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn.
If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.
The loop variable $i
is aliased to each element in the array in turn.
That means that if you change $i
you're changing the array.
This is what the for
statement in Perl is defined to do. See the documentation for Foreach Loops in man perlsyn
:
If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.