Reputation: 53
I have about 50 arrays filled with numbers and I have to report out a sum of all those elements for every array so the end result has 50 sums of individual arrays.
Is there any shorter way to do it rather than writing different for loop for every array?
I am a beginner with perl. Any helpful comments/suggestions would be appreciated.
This is my code so far:
for( $j = 1 ; $j <= 50 ; $j++ ) {
for ( @arr[$j] ) {
$sum[$j] += $_;
}
print $sum[$j];
}
Thank you!
Upvotes: 2
Views: 412
Reputation: 106365
For TIMTOWTDI!
# You cannot store arrays within arrays just with ((...), (...)) syntax,
# as this list will be flattened.
# Instead you should store _references_ to arrays, like this:
my @array_of_arrays = ([1..3], [4..6], [8..10]);
my @sums_of_arrays;
# ... then iterate over it, arrayref by arrayref
# (if `map` is somehow not for you) :)
for my $ref_arr (@array_of_arrays) {
my $arr_sum;
for my $el (@$ref_arr) {
$arr_sum += $el;
}
push @sums_of_arrays, $arr_sum;
}
Take note, though, that I consider this solution inferior to those given by @TLP and @SinanÜnür. ) For
construct is good when you need to do something (transform, for example) with each element of array (or array of arrays, as in this case). But here you just need something for each element - in other words, a map. )
Upvotes: 2
Reputation: 118118
use strict; use warnings;
use List::Util qw ( sum );
my %data = (
cats => [ map +(rand 100), 1 .. 10 ],
dogs => [ map +(100 - rand 100), 1 .. 20 ],
);
my %sums = map { $_ => sum(@{ $data{$_} }) } keys %data;
use YAML;
print Dump \%data, \%sums;
Upvotes: 4
Reputation: 67900
You can use List::Util and map
, assuming you have an array of arrays:
use strict;
use warnings;
use Data::Dumper;
use List::Util qw(sum);
my @arrays = (
[1,2,3],
[4,5,6],
[7,8,9]
);
my @sums = map sum(@$_), @arrays; # sum each array
print Dumper \@sums;
Output:
$VAR1 = [
'6', # sum of $arrays[0]
'15', # 1
'24' # 2
];
Upvotes: 7