perl - 在一行 Perl 中执行多个 +=

标签 perl variables equals

在 Perl 中,可以像这样实例化多个变量:

my ($a, $b, $c) = (1,2,3);

也可以用同样的方式重新分配多个变量值:

($a, $b, $c) = (4,5,6);

但是,当我尝试用加等于运算符做同样的事情时,

($a, $b, $c) += (7,8,9);

只有$c被正确添加,其他变量保持原值。这在 Perl 中应该是可能的,还是它只是偶然地部分工作并且它真的不能那样工作?如果后者是真的,有没有办法在一行中解决这个问题?

最佳答案

is it just partially working by accident and it really doesn't work that way?

是的。

标量上下文中的列表运算符依次计算其每个操作数,并返回其最后一个操作数的计算结果。所以你基本上是在做以下事情:

do { $a; $b; $c } += do { 7; 8; 9 };

这就是为什么你得到以下结果

Useless use of a constant (7) in void context at -e line 1.
Useless use of a constant (8) in void context at -e line 1.
Useless use of a variable in void context at -e line 1.
Useless use of a variable in void context at -e line 1.

is there a way to to this in one line?

当然,有无限多。这是三个:

$a += 7; $b += 8; $c += 9;

${$_->[0]} += $_->[1] for [\$a,7],[\$b,8],[\$c,9];

use List::MoreUtils qw( pairwise );
pairwise { $$a += $b; } @{[\$x,\$y,\$z]}, @{[7,8,9]};

关于perl - 在一行 Perl 中执行多个 +=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12684074/

相关文章:

jquery - 使用 Perl 模块 JSON 创建 JSON 对象

regex - Perl 正则表达式 : How to remove quotes inside quotes from CSV line

javascript - 如何将函数内部的动态变量传递给内部的另一个函数?

java - 我可以使用 .getClass() == .class 或 .getClass() == .class.getClass() 吗?

regex - 从数组中删除空白元素

regex - 为什么这种否定的后视被认为是成功的正则表达式匹配?

c# - 通过将方法作为变量发送来简化代码

string - autohotkey 将文本表达式分配给变量

javascript - 有没有办法打印动态变量?