简体   繁体   中英

for loop in perl

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM