任何人都可以解释在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元素). 从perldoc
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); }}总结
以上是内存溢出为你收集整理的perl foreach循环子程序全部内容,希望文章能够帮你解决perl foreach循环子程序所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)