in reply to Summing Up Array Elements By Group

For another alternate approach, first roll up the groups of 3 into array refs, then sum them up:

# Initial values my @arr = (1,2,3, 4,5,6, 7,8,9); # Replace with a set of array refs to 3-element arrays my $nblk = @arr / 3; my @a2; push @a2, [@arr[$_*3, $_*3+1, $_*3+2]] for (0..$nblk-1); # Sum up each array ref use List::Util qw(sum); my @a3 = map { sum @$_ } @a2;

Thus we end up with:

@a3 = ('6', '15', '24');

By itself, it's a pretty roundabout version of what ivancho did above. But if you can use the grouping in other places in the program, it can be useful to group them up like that early on.

Of course, if you don't, you skip the extra step and it collapses down to

use List::Util qw(sum); push @a3, sum @arr[$_*3, $_*3+1, $_*3+2] for (0..$nblk-1);

which is just another way of writing ivancho's second version.