Lists, Arrays, and Hashes
Foreach Array
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
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";
@scores ← 3, $bonus ← 1, $total ← 0
4my @scores→ 3 = (2, 4, 6);5my $bonus→ 1 = 1; #@bonus=0, 36my $total→ 0 = 0;$total ← 3
pass 1 of 38foreach my $score2 (@scores3) {9 $total→ 3 += $score2 + $bonus1;10}All 3 passes — pass 1 is the card above pass $score$total1 2 0 → 3 2 4 3 → 8 3 6 8 → 15 print "bonus=$bonus ";
12print "bonus=$bonus1\n";13print "total=$total15\n";14print "count=" . scalar(@scores3) . "\n";outputbonus=1 total=15 count=3
@scores ← 3, $bonus ← 0, $total ← 0
4my @scores→ 3 = (2, 4, 6);5my $bonus→ 0 = 0;6my $total→ 0 = 0;$total ← 2
pass 1 of 38foreach my $score2 (@scores3) {9 $total→ 2 += $score2 + $bonus0;10}All 3 passes — pass 1 is the card above pass $score$total1 2 0 → 2 2 4 2 → 6 3 6 6 → 12 print "bonus=$bonus ";
12print "bonus=$bonus0\n";13print "total=$total12\n";14print "count=" . scalar(@scores3) . "\n";outputbonus=0 total=12 count=3
@scores ← 3, $bonus ← 3, $total ← 0
4my @scores→ 3 = (2, 4, 6);5my $bonus→ 3 = 3;6my $total→ 0 = 0;$total ← 5
pass 1 of 38foreach my $score2 (@scores3) {9 $total→ 5 += $score2 + $bonus3;10}All 3 passes — pass 1 is the card above pass $score$total1 2 0 → 5 2 4 5 → 12 3 6 12 → 21 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
@scoresstarts as2,4, and6.$bonusis1.- Each loop adds the score plus the bonus.
- The final total is
15. | Score | Added with bonus1| 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