for loop in perl

前端 未结 4 1669
灰色年华
灰色年华 2021-01-22 15:35
my @array=(1..10);
for my $i (@array){$i++;}
print \"array is now:@array\";

this is changing the values of the array. Why?

4条回答
  •  迷失自我
    2021-01-22 16:09

    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.

提交回复
热议问题