Subroutines & signatures

Defining subroutines

Full

sub declarations, the parameter signature, and how a value gets returned.

A subroutine is declared with sub, a name, a signature in parentheses, and a body. Calling it binds the arguments to the signature's parameters.

A basic sub #

sub greet($name) {
    "Hello, $name!";
}
say greet("Ada");
Output
Hello, Ada!

Returning a value #

The value of the last expression is returned automatically — no return needed. Use an explicit return to leave early.

sub square($x) {
    $x ** 2;
}
say square(9);
Output
81

return stops the sub immediately; anything after it does not run:

sub double($x) {
    return $x * 2;
    say "never reached";
}
say double(5);
Output
10

Notes #