Perl Subroutines
Define a sub that reads its arguments from @_.
Perl
use strict;
use warnings;
sub average {
my @values = @_;
my $total = 0;
$total += $_ for @values;
return $total / @values;
}
print average(82, 91, 76, 95), "\n";Output
86
Explanation
A subroutine is declared with sub. All of its arguments arrive in the special array @_, and my @values = @_ copies them into a named variable so the body is easier to read.
return sends back a value. Dividing by @values uses the array in numeric context, which is its length. A subroutine defined before it is used can be called with parentheses and a list of arguments.
Explore the dry run
Guided walkthroughReady
1
use strict;2
use warnings;3
4
sub average {5
my @values = @_;6
my $total = 0;7
$total += $_ for @values;8
return $total / @values;9
}10
11
print average(82, 91, 76, 95), "\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 |
|---|---|---|---|
| Define a subroutine named average. | — | — | |
| Copy the four arguments into @values. | @values = (82, 91, 76, 95) | — | |
| Sum the values. | $total = 344 | — | |
| 344 / 4 is 86, printed without a decimal point. | return = 86 | 86 |
Cost and common mistakes
O(n) time and space for the copy.
- Dividing by an empty @values dies with 'Illegal division by zero'.
- Without my, variables become globals, which use strict reports as an error.
Try it yourself
Predict average(1, 2).
Reveal answer and reasoning
3 / 2 is 1.5, so it prints 1.5.