O'Reilly logo

Perl 6 and Parrot Essentials, Second Edition by Leopold Tötsch, Dan Sugalski, Allison Randal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required