5.7 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.



Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition
ISBN: 059600737X
EAN: 2147483647
Year: 2003
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net