Chapter 5. Subroutines

Subroutines are reusable units of code. They can be called from just about anywhere, and return control to the point of the call when they finish executing. They can be passed zero or more arguments[9] and return zero or more results. Subroutines can be named or anonymous. They can be lexically scoped, package scoped, or globally scoped. “Multi” subs allow multiple subroutines to have the same name as long as they have different parameter lists.

Methods are significantly different from subroutines. In Perl 6, they’re even distinguished by a separate keyword, method. These differences will be discussed in Chapter 6.

Using Subroutines

The most basic subroutine declaration is simply the sub keyword, followed by the name of the sub, followed by the block that defines the sub:

sub alert {
    print "We have normality.";
}

The simplest subroutine call is just the subroutine name followed by a comma-separated list of variables or values:

$result = sum($a, $b, 42, 57);

Arguments are also sometimes passed as anonymous pairs:

$result = sum(first => 12, second => 21);

Parentheses are optional on calls to subroutines that have been predeclared, but required for all other calls. Including the & sigil before the subroutine name in a call will not turn off signature checking. In fact, in most contexts prefixing the subroutine name with & will return a reference to the subroutine instead of calling the subroutine.

[9] Following the example set in Apocalypse 6, throughout this chapter ...

Get Perl 6 and Parrot Essentials, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.