Creating and calling subroutines
The sub
keyword creates a subroutine. A typical subroutine has a name, a list of formal parameters, and a body. However, both the name and the parameter list are optional. In Chapter 1, What is Perl 6?, we already created a subroutine to add two numbers. Let's recall it here:
sub add($x, $y) { return $x + $y; }
Here, add
is the name, which will later be used to call a sub. It is followed by a list of the sub's parameters—($x, $y)
. The body of the subroutine is enclosed inside a pair of curly braces—{return $x + $y;}
.
To call a subroutine, use the name again and pass the actual parameters in parentheses:
my $a = 17; my $b = 71; my $sum = add($a, $b); say "Sum of $a and $b is $sum"; # Sum of 17 and 71 is 88
There are two ways a sub can return a value. The first we just saw in the add
function. It uses an explicit return
keyword, as you can see here:
return $a + $b;
After the return
call, a sub stops its execution. Any extra code after the return
statement will...