Perl adding array with another array
I cam across the code below online where it's trying to add two array. Can anyone explain what it is calculating to get 14?
my @a = (1,2,5)+(8,9); print "@a"; output: 14
Output is 14 as $a is 14 => 5+9
+ operator imposes scalar context on both lists so last elements are taken and added,
# in scalar context $x is assigned with last element my $x = (1,2,5); print "\$x is $x\n";
outputs $x is 5
warnings pragma would also complain, giving you a hint that something fishy is going on,
Useless use of a constant (8) in void context
my @a = (1,2,5)+(8,9);
When using a list in a scalar context, the last element is returned. Consult What is the difference between a list and an array? for details.
Therefore the above two lists reduce to:
my @a = 5 + 9;
Which mathematically equals:
my @a = (14);