为什么 Perl foreach 变量赋值会修改数组中的值? [英] Why is Perl foreach variable assignment modifying the values in the array?

查看:56
本文介绍了为什么 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.

这篇关于为什么 Perl foreach 变量赋值会修改数组中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆