Perl Arrays
Store a list in an @array and loop over it.
On this page
Perl scalars.
- Store a list in an @array and loop over it.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
use strict;
use warnings;
my @scores = (82, 91, 76);
push @scores, 95;
my $total = 0;
$total += $_ for @scores;
print scalar(@scores), " ", $total, "\n";4 344
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
use strict;use warnings; my @scores = (82, 91, 76);push @scores, 95;my $total = 0;$total += $_ for @scores;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 |
Behind the scenes
How Perl processes this code
Perl compiles the script internally before executing it. strict and warnings help identify mistakes.
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.