Accumulate list values into one total.

reduce-sum A reduce-style pass combines many values into one value. This example uses a small accumulator so each step stays visible.

Reduce Sum

bonus
reduce_sum.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;

my $bonus = 0;
my @points = (2, 4, 6);
my $total = $bonus;

for my $point (@points) {
    $total = $total + $point;
}

print "bonus=$bonus\n";
print "total=$total\n";
use strict;
use warnings;

my $bonus = 5;
my @points = (2, 4, 6);
my $total = $bonus;

for my $point (@points) {
    $total = $total + $point;
}

print "bonus=$bonus\n";
print "total=$total\n";
  1. $bonus ← 0, @points ← 3, $total ← 0

    4my $bonus→ 0 = 0; #@bonus=55my @points→ 3 = (2, 4, 6);6my $total→ 0 = $bonus0;
  2. $total ← 2

    pass 1 of 3
    8for my $point2 (@points3) {9    $total→ 2 = $total + $point2;10}
    All 3 passes — pass 1 is the card above
    pass$point$total
    120 2
    242 6
    366 12
  3. print "bonus=$bonus ";

    12print "bonus=$bonus0\n";13print "total=$total12\n";
    outputbonus=0
    total=12
  1. $bonus ← 5, @points ← 3, $total ← 5

    4my $bonus→ 5 = 5;5my @points→ 3 = (2, 4, 6);6my $total→ 5 = $bonus5;
  2. $total ← 7

    pass 1 of 3
    8for my $point2 (@points3) {9    $total→ 7 = $total + $point2;10}
    All 3 passes — pass 1 is the card above
    pass$point$total
    125 7
    247 11
    3611 17
  3. print "bonus=$bonus ";

    12print "bonus=$bonus5\n";13print "total=$total17\n";
    outputbonus=5
    total=17