为什么 Perl foreach 变量赋值会修改数组中的值?

问题描述:

好的,我有以下代码:

use strict;
my @ar = (1, 2, 3);
foreach my $a (@ar)
{
  $a = $a + 1;
}

print join ", ", @ar;

和输出?

2、3、4

什么鬼?为什么这样做?这会一直发生吗?$a 不是真正的局部变量吗?他们在想什么?

What the heck? Why does it do that? Will this always happen? is $a not really a local variable? What where they thinking?

Perl 有很多这些几乎奇怪的语法东西,它们极大地简化了常见任务(例如迭代列表和以某种方式更改内容),但可能会出错如果你不知道他们,你就起来.

Perl has lots of these almost-odd syntax things which greatly simplify common tasks (like iterating over a list and changing the contents in some way), but can trip you up if you're not aware of them.

$a 别名为数组中的值 - 这允许您在循环内修改数组.如果您不想这样做,请不要修改 $a.

$a is aliased to the value in the array - this allows you to modify the array inside the loop. If you don't want to do that, don't modify $a.