Consider:
my @array = (1..10);
for my $i (@array) {
$i++;
}
print "array is now: @array";
This is changing the values of the array. Why?
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.
$i variables in two different scopes: one limited to the for loop and the original one outside. The original $i will still be 5 after the loop.This is documented behaviour. See perldoc perlsyn:
The
foreachloop 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
foreachloop index variable is an implicit alias for each item in the list that you're looping over.