How to sum two lists element-wise
list, perl
Solution
No, it's because the expression `($i, $j) += (something, 1)` parses as adding `1` to `$j` only, leaving `$i` hanging in void context. Perl 5 has no hyper-operators or automatic zipping for the assignment operators such as `+=`. This works:
my ($i, $j) = (0, 0);
foreach my $line (<INFILE>) {
my ($this_i, $this_j) = split /\t/, $line;
$i += $this_i;
$j += $this_j;
}
You can avoid the repetion by using a compound data structure instead of named variables for the columns.
Problem
I want to parse a file line by line, each of which containing two integers, then sum these values in two distinct variables. My naive approach was like this: ``` my $i = 0; my $j = 0; foreach my $line (<INFILE>) { ($i, $j) += ($line =~ /(\d+)\t(\d+)/); } ``` But it yields the following warning: Useless use of private variable in void context hinting that resorting to the += operator triggers evaluation of the left-hand side in scalar instead of list context (please correct me if I'm wrong on this point). Is it possible to achieve this elegantly (possibly in one line) without resorting to arrays or intermediate variables? Related question: How can I sum arrays element-wise in Perl?