tags:

views:

180

answers:

6

How to find the sum of all values from two different arrays in Perl?

@array1 = (1, 2, 3);
@array2 = (10, 10, 10);

@sumofarray1and2 = ?

So I figured I can do two kinds of things here. I can do two foreach loops and add contents of @array1 and @array2 first then get the sum of both.

+1  A: 

For the summing, use List::Util. For the "two arrays", just put them in a list and you'll get a list of all their values.

#!/usr/bin/perl

use strict;
use warnings;
use List::Util;

my @foo = (1,2,3);
my @bar = (4,5,6);

print List::Util::sum(@foo, @bar), "\n";
David Dorward
+2  A: 
use List::Util qw(sum);
@array1=(1,2,3);
@array2=(10,10,10);
print sum(@array1, @array2);
Mark Byers
+8  A: 
my $sum = 0;
$sum += $_ for (@array1, @array2);
eugene y
Modules are cool and everything, but it chafes me to see people recommend a module for something that could be done in two lines of conventional Perl. And if you are leaning the language or otherwise asking a simple question, figuring out how to do the job without modules is usually a more valuable experience.
mobrule
And some people call Perl a write-only language.
+3  A: 

Since the sum of both lists is already here, this is how to sum the lists element wise:

my @sums = map {$array1[$_] + $array2[$_]} 0 .. $#array1;

This assumes the lists are the same length.

This code uses the map function which applies its block to a list, and generates a new list from the block's return value. The block shown will add elements from each array at index $_. $_ is set by map to the values of its passed in list. $#array1 is the index of the last element, in this case 2. That makes the list passed into map (0, 1, 2).

Eric Strom
A: 
#!/usr/bin/perl
use strict;
use warnings;

use List::Util qw( sum );
use List::MoreUtils qw( pairwise );

our ($a, $b);
my @array1 = (1, 2, 3);
my @array2 = (10, 10, 10);

my @sum = pairwise { $a + $b } @array1, @array2;

printf "%s : %d\n", "@sum", sum @sum;

Output:

C:\Temp> s
11 12 13 : 36
Sinan Ünür
+1  A: 

Another way to do it is with the fold family, e.g., reduce:

#! /usr/bin/perl -l

use List::Util qw/ reduce /;

@array1 = (1, 2, 3);
@array2 = (10, 10, 10);

print reduce { $a + $b } @array1, @array2;
Greg Bacon