In Perl it is possible to instantiate multiple variables like so:
my ($a, $b, $c) = (1,2,3);
It is also possible to reassign multiple variable values the same way:
($a, $b, $c) = (4,5,6);
However, when I try to do the same thing with the plus equals operator,
($a, $b, $c) += (7,8,9);
only $c is properly added and the other variables remain their original value. Is this something that should be possible in Perl, or is it just partially working by accident and it really doesn't work that way? If the latter is true, is there a way to to this in one line?
is it just partially working by accident and it really doesn't work that way?
Yes.
The list operator in scalar context evaluates each of its operands in turn, and returns that to which its last operand evaluates. So you're basically doing the following:
do { $a; $b; $c } += do { 7; 8; 9 };
That's why you're getting the following
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?
Sure, there are infinitely many. Here are three:
$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]};
The longhand version of += should work:
($a,$b,$c) = ($a+7,$b+8,$c+9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With