A foreach loop visits each array value and can accumulate a result.

foreach `foreach` runs the loop body once for each value in a list or array.

Foreach Array

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

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

foreach my $score (@scores) {
    $total += $score + $bonus;
}

print "bonus=$bonus\n";
print "total=$total\n";
print "count=" . scalar(@scores) . "\n";
use strict;
use warnings;

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

foreach my $score (@scores) {
    $total += $score + $bonus;
}

print "bonus=$bonus\n";
print "total=$total\n";
print "count=" . scalar(@scores) . "\n";
use strict;
use warnings;

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

foreach my $score (@scores) {
    $total += $score + $bonus;
}

print "bonus=$bonus\n";
print "total=$total\n";
print "count=" . scalar(@scores) . "\n";
  1. @scores ← 3, $bonus ← 1, $total ← 0

    4my @scores→ 3 = (2, 4, 6);5my $bonus→ 1 = 1; #@bonus=0, 36my $total→ 0 = 0;
  2. $total ← 3

    pass 1 of 3
    8foreach my $score2 (@scores3) {9    $total→ 3 += $score2 + $bonus1;10}
    All 3 passes — pass 1 is the card above
    pass$score$total
    120 3
    243 8
    368 15
  3. print "bonus=$bonus ";

    12print "bonus=$bonus1\n";13print "total=$total15\n";14print "count=" . scalar(@scores3) . "\n";
    outputbonus=1
    total=15
    count=3
  1. @scores ← 3, $bonus ← 0, $total ← 0

    4my @scores→ 3 = (2, 4, 6);5my $bonus→ 0 = 0;6my $total→ 0 = 0;
  2. $total ← 2

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

    12print "bonus=$bonus0\n";13print "total=$total12\n";14print "count=" . scalar(@scores3) . "\n";
    outputbonus=0
    total=12
    count=3
  1. @scores ← 3, $bonus ← 3, $total ← 0

    4my @scores→ 3 = (2, 4, 6);5my $bonus→ 3 = 3;6my $total→ 0 = 0;
  2. $total ← 5

    pass 1 of 3
    8foreach my $score2 (@scores3) {9    $total→ 5 += $score2 + $bonus3;10}
    All 3 passes — pass 1 is the card above
    pass$score$total
    120 5
    245 12
    3612 21
  3. print "bonus=$bonus ";

    12print "bonus=$bonus3\n";13print "total=$total21\n";14print "count=" . scalar(@scores3) . "\n";
    outputbonus=3
    total=21
    count=3

Add Each Score

  1. @scores starts as 2, 4, and 6.
  2. $bonus is 1.
  3. Each loop adds the score plus the bonus.
  4. The final total is 15. | Score | Added with bonus 1 | Running total | | --- | --- | --- | | 2 | 3 | 3 | | 4 | 5 | 8 | | 6 | 7 | 15 |

Exercise: foreach_array.pl

Loop over scores, add each score plus a bonus, and print the total and count