How to find the sum of all values f开发者_运维问答rom 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.
my $sum = 0;
$sum += $_ for (@array1, @array2);
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)
.
use List::Util qw(sum);
@array1=(1,2,3);
@array2=(10,10,10);
print sum(@array1, @array2);
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";
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;
#!/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
精彩评论