@H_301_2@
以下代码给出了一条错误消息:
#!/usr/bin/perl -w foreach my $var (0,1,2){ $var += 2; print "$var\n"; }
在test.pl第4行尝试修改只读值.
解决方法
在foreach $var(@list)构造中,$var变为别名的循环元素,因为$var的内存地址与@list的元素的地址相同.因此,您的示例代码尝试修改只读值,并获得错误消息.
这个小脚本将演示foreach构造中发生的事情:
my @a = (0,2); print "Before: @a\n"; foreach my $var (@a) { $var += 2; } print "After: @a\n"; Before: 0 1 2 After: 2 3 4
附加信息:从perlsyn
开始的This item很容易掩盖,但给出了整个独家新闻:
Foreach loops
…
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.
@H_301_2@