Parameters

One of the most significant additions to subroutines in Perl 6 is named formal parameters. The parameter list, often called the signature of the subroutine, is part of the subroutine declaration:

sub standardize ($text, $method) {
    my $clean;
    given $method {
        when 'length' { $clean = wrap($text, 72); }
        when 'lower'  { $clean = lowercase($text); }
         . . . 
    }
    return $clean;
}

The subroutine standardize has two scalar parameters, $text and $method, so it is called with two arguments, each a scalar value. The parameters are lexical variables within the body of the sub. They never need to be explicitly declared as my, even under use strict because they’re declared by the subroutine declaration.

In a sub with no parameter list, all arguments are passed in the @_ array:

sub sum {
    my $sum;
    for @_ -> $number {
        $sum += $number;
    }
    return $sum;
}

Subroutines with defined parameter lists don’t get an @_ array.[10] If you want a subroutine that takes no arguments (and complains when arguments are passed), define it with an empty parameter list ( ).

Subroutine calls normally provide a nonflattening list context, which means that any array or hash passed into a subroutine is treated as a single argument. An array parameter in the signature expects to be passed an actual array or arrayref argument, and a hash parameter expects a hash or hashref argument:

sub whole (@names, %flags) {
     . . . 
}

whole(@array, %hash);

Optional Parameters

Every subroutine call checks its signature to make sure the arguments ...

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.