Perl Arrays
Store a list in an @array and loop over it.
Perl
use strict;
use warnings;
my @scores = (82, 91, 76);
push @scores, 95;
my $total = 0;
$total += $_ for @scores;
print scalar(@scores), " ", $total, "\n";Output
4 344
Explanation
A Perl array variable starts with @. push adds elements to the end. Using an array in scalar context, as scalar(@scores) does, gives its length.
The statement modifier $total += $_ for @scores runs the addition once for each element, with $_ holding the current one. my declares the variables lexically, and use strict makes the compiler enforce it.
Explore the dry run
Guided walkthroughReady
1
use strict;2
use warnings;3
4
my @scores = (82, 91, 76);5
push @scores, 95;6
my $total = 0;7
$total += $_ for @scores;8
print scalar(@scores), " ", $total, "\n";Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| An array of three numbers. | @scores = (82, 91, 76) | — | |
| Append a fourth element. | @scores = (82, 91, 76, 95) | — | |
| Add each element to the total. | $total = 344 | — | |
| Print the length and the sum. | $total = 344 | 4 344 |
Cost and common mistakes
push is amortized O(1); the loop is O(n).
- print @scores without separators glues the elements together; join them explicitly.
- The last index is $#scores, which is one less than the length.
Try it yourself
Print the first element.
Reveal answer and reasoning
print $scores[0]; uses $ because a single element is a scalar. It prints 82.