Multi Subroutines

You can define multiple routines with the same name but different signatures. These are known as “multisubs” and are defined with the multi keyword before sub. They’re useful if you want a routine that can handle different types of arguments in different ways, but still appear as a single subroutine to the user. For example, you might define an add multisub with different behavior for integers, floats, and certain types of numeric objects:

multi sub add (Int $first, Int $second) { . . . }
multi sub add (Num $first, Num $second) { . . . }
multi sub add (Imaginary $first, Imaginary $second) { . . . }
multi sub add (MyNum $first, MyNum $second) { . . . }

When you later call the routine:

add($apples, $oranges);

it will dispatch to the right version of add based on the types of the arguments passed to it. The parameters used for dispatch selection are called invocants. If you want to use a limited set of parameters as invocants, mark the boundary between invocant parameters and the rest of the signature with a semicolon:

multi sub add (Int $first, Int $second: Int $third) { . . . }

This version of add will dispatch based on the types of the first two arguments passed in, and ignore the type of the third.

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.