Lists, Arrays, and Hashes
Foreach Array
A foreach loop visits each array value and can accumulate a result.
Foreach Array
foreach_array.pl
use strict;
use warnings;
my @scores = (2, 4, 6);
my $bonus = ;
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 = ;
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 = ;
my $total = 0;
foreach my $score (@scores) {
$total += $score + $bonus;
}
print "bonus=$bonus\n";
print "total=$total\n";
print "count=" . scalar(@scores) . "\n";
foreach
`foreach` runs the loop body once for each value in a list or array.