Perl Subroutines
Define a sub that reads its arguments from @_.
On this page
Perl arrays.
- Define a sub that reads its arguments from @_.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
use strict;
use warnings;
sub average {
my @values = @_;
my $total = 0;
$total += $_ for @values;
return $total / @values;
}
print average(82, 91, 76, 95), "\n";86
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
use strict;use warnings; sub average { my @values = @_; my $total = 0; $total += $_ for @values; return $total / @values;} 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 |
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
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.