我知道perl中的子程序通过引用传递arg.但是在下面的代码中,子例程中的foreach循环不应该更改@list的值,因为my $i应该创建一个新的词法范围var $i.对$i的任何赋值都应该是词法范围,但不能更改@list值.
任何人都可以解释在foreach循环中发生的事情导致值更改为@list吗?
sub absList { foreach my $i (@_) { $i = abs($i); } } @list = (-2,2,4,-4); absList(@list); print "@list";
输出:
2 2 4 4
解决方法
由于
foreach
特征,$i被别名化为@_数组的元素(并且@_元素别名为@list的@list元素).
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.
如果你想避免这种行为,不要直接在@_数组上迭代,即.
sub absList { my @arr = @_; foreach my $i (@arr) { $i = abs($i); } }