Defines a function (subprogram).
Syntax
sub name { ... return ...; }Description
Defined with sub. Arguments come in the @_ array: $_[0] is the first, $_[1] is the second. Values are returned with return.
Example
sub addUp {
return $_[0] + $_[1];
}
print addUp(8, 9), "\n";Expected output
17
When to use?
Preventing code repetition.
Common mistakes
- ⚠️ Arguments are retrieved from the @_ array: my ($a, $b) = @_;