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
1use strict;
2use warnings;
3
4my @scores = (82, 91, 76);
5push @scores, 95;
6my $total = 0;
7$total += $_ for @scores;
8print 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading