class Signature

Parameter list pattern

class Signature { ... }

A signature is a static description of the parameter list of a code object. That is, it describes what and how many arguments you need to pass to the code or function in order to call it.

Passing arguments to a signature binds the arguments, contained in a Capture, to the signature.

Signature Literals

Signatures appear in parenthesis after subroutine and method names, on blocks after a -> or <-> arrow, as the input to variable declarators like my, or as a separate term starting with a colon.

sub f($x) { }
#    ^^^^ Signature of sub f
method x() { }
#       ^^ Signature of a method
my $s = sub (*@a) { }
#           ^^^^^ Signature of an anonymous function

for @list -> $x { }
#            ^^   Signature of a block

my ($a, @b) = 5, (6,7,8);
#  ^^^^^^^^ Signature of a variable declarator

my $sig = :($a, $b);
#          ^^^^^^^^ Standalone Signature object

Signature literals can be used to define the signature of a callback or a closure.

sub f(&c:(Int)){}
sub will-work(Int){}
sub won't-work(Str){}
f(&won't-work); # fails at runtime
f(-> Int { 'this works too' } );

Parameter Separators

A signature consists of zero or more parameters, separated by comma.

:($a, @b, %c)
sub add ($a, $b) { $a + $b }

As an exception the first parameter may be followed by a colon instead of a comma to mark the invocant of a method. The invocant is the object that was used to call the method, which is usually bound to self. By specifying it in the signature, you can change the variable name it is bound to.

:($a: @b, %c)       # first argument is the invocant

class Foo {
    method whoami ($me:) {
        "Well I'm class $me.^name(), of course!"
say Foo.whoami; # => Well I'm class Foo, of course!

Type Constraints

Parameters can optionally have a type constraint (the default is Any). These can be used to restrict the allowed input to a function.

:(Int $a, Str $b)

sub divisors (Int $n) { $_ if $n %% $_ for 1..$n }
divisors 2.5; # !!! Calling 'divisors' will never work with argument types (Rat)

Anonymous parameters are fine too, if a parameter is only needed for its type constraint.

:($, @, %a)               # two anonymous and a "normal" parameter
:(Int, Positional)  # just a type is also fine (two parameters)
sub baz (Str) { "Got passed a Str" }

Type constraints may also be type captures.

In addition to those nominal types, additional constraints can be placed on parameters in the form of code blocks which must return a true value to pass the type check

sub f(Real $x where { $x > 0 }, Real $y where { $y >= $x }) { }

In fact it doesn't need to be a code block, anything on the right of the where-block will be used to smart-match the argument against it. So you can also write

multi factorial(Int $ where 0) { 1 }
multi factorial(Int $x)        { $x * factorial($x - 1) }

The first of those can be shortened to

multi factorial(0) { 1 }

i.e., you can use a literal directly as a type and value constraint on an anonymous parameter.

Constraining Defined and Undefined Values

Normally, a type constraint only checks whether the value passed is of the correct type.

sub limit-lines (Str $s, Int $limit) {
    my @lines = $s.lines;
    @lines[0 .. min @lines.elems, $limit].join("\n")
say (limit-lines "a \n b \n c \n d \n", 3).perl; # "a \n b \n c "
say limit-lines Str,      3;  # Uh-oh. Dies with "Cannot call 'lines';"
say limit-lines "a \n b", Int # Always returns the max number of lines

In this case, we really only want to deal with defined strings. To do this, we use the :D type constraint.

sub limit-lines (Str:D $s, Int $limit) {
# Dies with "Parameter '$s' requires an instance, but a type object was passed
#   in sub limit-lines"
say limit-lines Str, 3;

This is much better than the way the program failed before, since here the reason for failure is clearer.

It's also possible undefined types are the only ones that make sense for a routine to accept. This can be constrained with the :U type constraint. For example, we can turn the &limit-lines into a multi function to make use of the :U constraint.

multi limit-lines (Str $s, Int:D $limit) {
multi limit-lines (Str $s, Int:U $) { $s }
say limit-lines "a \n b \n c", Int; # "a \n b \n c"

For explicitly indicating the normal behaviour, :_ can be used, but this is unnecessary. :(Num:_ $) is the same as :(Num $).

Constraining Return Types

The token --> followed by a type will force a type check on successful execution of a routine. The return type arrow has to be placed at the end of the parameter list. The keyword returns following a signature declaration has the same function. Nil is considered as being defined for the type check.

sub foo(--> Int) { 1 };
sub foo() returns Int { 1 };
sub does-not-work(--> Int) { "" }; # throws X::TypeCheck::Return

If the type constraint is a constant expression, it is used as the return value of the routine. Any return statement in that routine has to be argumentless.

sub foo(--> 123) { return }

Nil and Failure are always allowed as return types, regardless of any type constraint.

sub foo(--> Int) { Nil };
say foo.perl; # Nil

Type captures and coercion types are not supported.

Slurpy (A.K.A. Variadic) Parameters

An array or hash parameter can be marked as slurpy by leading asterisk(s), which means it can bind to an arbitrary amount of arguments (zero or more).

These are called "slurpy" because they slurp up any remaining arguments to a function, like someone slurping up noodles.

:($a, @b)              # exactly two arguments, where the second one must be Positional
:($a, *@b)          # at least one argument, @b slurps up any beyond that
:(*%h)              # no positional arguments, but any number of named arguments
sub one-arg (@)     { }
sub slurpy  (*@) { }
one-arg(5, 6, 7) ; # !!! too many arguments
one-arg (5, 6, 7); # ok, same as one-arg((5,6,7))
slurpy  (5, 6, 7); # ok
one-arg  5, 6, 7 ; # !!! too many arguments
slurpy   5, 6, 7 ; # ok
sub named-names (*%named-args) { %named-args.keys }
say named-names :foo(42) :bar<baz> # => foo bar

Note that positional parameters aren't allowed after slurpy parameters.

:(*@args, $last) # !!! Cannot put required parameter after variadic parameters

Slurpy parameters declared with one asterisk will flatten arguments by dissolving one or more layers of bare Iterables. Slurpy parameters declared with two stars do not do so:

sub a (*@a) { @a.join("|").say };
a(1,[1,2],([3,4],5)); # 1|1|2|3|4|5
sub b (**@b) { @b.join("|").say };
b(1,[1,2],([3,4],5)); # 1|1 2|3 4 5

Normally a slurpy parameter will create an Array, create a new Scalar container for each argument, and assign the value from each argument to those Scalars. If the original argument also had an intermediary Scalar it is bypassed during this process, and is not available inside the called function.

Slurpy parameters have special behaviors when combined with some traits and modifiers, as described below.

Type Captures

Type Captures allow to defer the specification of a type constraint to the time the function is called. They allow to refer to a type both in the signature and the function body.

sub f(::T $p1, T $p2, ::C){
    # $p1 and $p2 are of the same type T, that we don't know yet
    # C will hold a type we derive from a type object or value
    my C $closure = $p1 / $p2;
        return sub (T $p1) {
                $closure * $p1;

# The first parameter is Int and so must be the 2nd.
# We derive the 3rd type from calling the operator that is used in &f.
my &s = f(10, 2, /;
say s(2); # 10 / 2 * 2 == 10

Positional vs. Named

A parameter can be positional or named. All parameters are positional, except slurpy hash parameters and parameters marked with a leading colon :.

:($a)               # a positional parameter
:(:$a)              # a named parameter of name 'a'
:(*@a)              # a slurpy positional parameter
:(*%h)              # a slurpy named parameter

On the caller side, positional arguments are passed in the same order as the parameters were declared.

sub pos($x, $y) { "x=$x y=$y" }
pos(4, 5);                          # x=4 y=5

In the case of named arguments and parameters, only the name is used for mapping arguments to parameters

    sub named(:$x, :$y) { "x=$x y=$y" }
    named( y => 5, x => 4);             # x=4 y=5

It is possible to have a different name for a named parameter than the variable name:

sub named(:official($private) { "Official business!" if $private }
named :official;

Aliases are also possible that way:

sub paint( :color(:colour($c)) ) { }    # 'color' and 'colour' are both OK
sub paint( :color(:$colour) ) { }       # same API for the caller

A function with named arguments can be called dynamically, dereferencing a Pair with | to turn it into a named argument.

multi f(:$named){ note &?ROUTINE.signature };
multi f(:$also-named){ note &?ROUTINE.signature };
for 'named', 'also-named' -> $n {
	f(|($n => rand))                    # «(:$named)␤(:$also-named)␤»

my $pair = :named(1);
f |$pair;                               # «(:$named)␤»

The same can be used to convert a Hash into named arguments.

my %pairs = also-named => 4;
f |%pairs;                              # «(:$also-named)␤»

Optional and Mandatory Parameters

Positional parameters are mandatory by default, and can be made optional with a default value or a trailing question mark:

:(Str $id)          # required parameter
:($base = 10)       # optional parameter, default value 10
:(Int $x?)          # optional parameter, default is the Int type object

Named parameters are optional by default, and can be made mandatory with a trailing exclamation mark:

:(:%config)         # optional parameter
:(:$debug = False)  # optional parameter, defaults to False
:(:$name!)          # mandatory 'name' named parameter

Default values can depend on previous parameters, and are (at least notionally) computed anew for each call

:($goal, $accuracy = $goal / 100);
:(:$excludes = ['.', '..']);        # a new Array for every call

Destructuring Parameters

Parameters can be followed by a sub-signature in brackets, which will destructure the argument given. The destructuring of a list is just its elements:

    sub first (@array ($first, *@rest)) { $first }


    sub first ([$f, *@]) { $f }

While the destructuring of a hash is its pairs:

    sub all-dimensions (% (:length(:$x), :width(:$y), :depth(:$z))) {
        $x andthen $y andthen $z andthen True

In general, an object is destructured based on its attributes. A common idiom is to unpack a Pair's key and value in a for loop:

    for @guest-list.pairs -> (:key($index), :value($guest)) {

However, this unpacking of objects as their attributes is only the default behavior. To make an object get destructured differently, change its Capture method.

Capture Parameters

Prefixing a parameter with a vertical bar | makes the parameter a Capture, using up all the remaining positional and named arguments.

This is often used in proto definitions (like proto foo (|) {*}) to indicate that the routine's multi definitions can have any type constraints. See proto for an example.

Parameter Traits and Modifiers

By default, parameters are bound to their argument and marked as read-only. One can change that with traits on the parameter.

The is copy trait causes the argument to be copied, and allows it to be modified inside the routine

sub count-up ($x is copy) {
    $x = Inf if $x ~~ Whatever;
    .say for 1..$x;

The is rw trait makes the parameter only bind to a variable (or other writable container). Assigning to the parameter changes the value of the variable at the caller side.

sub swap($x is rw, $y is rw) {
    ($x, $y) = ($y, $x);

On slurpy parameters, is rw is reserved for future use by language designers.

The is raw trait is automatically applied to parameters declared with a backslash as a "sigil", and may also be used to make normally sigiled parameters behave like these do. In the special case of slurpies, which normally produce an Array full of Scalars as described above, is raw will instead cause the parameter to produce a List. Each element of that list will be bound directly as raw parameter.


method params

method params(Signature:D:) returns Positional

Returns the list of Parameter objects that make up the signature.

method arity

method arity(Signature:D:) returns Int:D

Returns the minimal number of positional arguments required to satisfy the signature.

method count

method count(Signature:D:) returns Real:D

Returns the maximal number of positional arguments which can be bound to the signature. Returns Inf if there is a slurpy positional parameter.

method returns

Whatever the Signature's return constraint is:

:($a, $b --> Int).returns # Int

method ACCEPTS

multi method ACCEPTS(Signature:D: Capture $topic)
multi method ACCEPTS(Signature:D: @topic)
multi method ACCEPTS(Signature:D: %topic)
multi method ACCEPTS(Signature:D: Signature $topic)

The first three see if the argument could be bound to the capture, i.e., if a function with that Signature would be able to be called with the $topic:

(1,2, :foo) ~~ :($a, $b, :foo($bar))    # True
<a b c d> ~~ :(Int $a)                  # False

The last returns True if anything accepted by $topic would also be accepted by the Signature.

:($a, $b) ~~ :($foo, $bar, $baz?)   # True
:(Int $n) ~~ :(Str)                 # False

Type graph

Below you should see a clickable image showing the type relations for Signature that links to the documentation pages for the related types. If not, try the PNG version instead.

perl6-type-graph Signature Signature Any Any Signature->Any Mu Mu Any->Mu

Routines supplied by class Any

Signature inherits from class Any, which provides the following methods:

method ACCEPTS

Defined as:

multi method ACCEPTS(Any:D: Mu $other)



Returns True if $other === self (i.e. it checks object identity).

Many built-in types override this for more specific comparisons

method any

Defined as:

method any() returns Junction:D



Interprets the invocant as a list and creates an any-Junction from it.

say so 2 == <1 2 3>.any;        # True
say so 5 == <1 2 3>.any;        # False

method all

Defined as:

method all() returns Junction:D



Interprets the invocant as a list and creates an all-Junction from it.

say so 1 < <2 3 4>.all;         # True
say so 3 < <2 3 4>.all;         # False

method one

Defined as:

method one() returns Junction:D


Interprets the invocant as a list and creates a one-Junction from it.

say so 1 == (1, 2, 3).one;      # True
say so 1 == (1, 2, 1).one;      # False

method none

Defined as:

method none() returns Junction:D



Interprets the invocant as a list and creates a none-Junction from it.

say so 1 == (1, 2, 3).none;     # False
say so 4 == (1, 2, 3).none;     # True

method list

Interprets the invocant as a list, and returns that List.

say 42.list.^name;           # List
say 42.list.elems;           # 1

method push

The method push is defined for undefined invocants and allowes for autovivifying undefined to an empty Array, unless the undefined value implements Positional already. The argument provided will then be pushed into the newly created Array.

my %h;
dd %h<a>; # Any (and therefor undefined)
%h<a>.push(1); # .push on Any
dd %h; # «Hash %h = {:a($[1])}␤» # please not the Array

routine reverse

Defined as:

multi sub    reverse(*@list ) returns List:D
multi method reverse(List:D:) returns List:D



Returns a list with the same elements in reverse order.

Note that reverse always refers to reversing elements of a list; to reverse the characters in a string, use flip.


say <hello world!>.reverse      #  world! hello
say reverse ^10                 # 9 8 7 6 5 4 3 2 1 0

method sort

Sorts iterables with infix:<cmp> or given code object.


say <b c a>.sort;                           # a b c
say 'bca'.comb.sort.join;                   # abc
say 'bca'.comb.sort({$^b cmp $^a}).join;    # cba
say '231'.comb.sort(&infix:«<=>»).join;     # 123

method map

Defined as:

proto method map(|) is nodal { * }
multi method map(\SELF: &block;; :$label, :$item)
multi method map(HyperIterable:D: &block;; :$label)

map will iterate over the invocant and apply the number of positional parameters of the code object from the invocant per call. The returned values of the code object will become elements of the returned Seq.

method flat

Interprets the invocant as a list, flattens it, and returns that list. Please note that .flat will not solve the halting problem for you. If you flat an infinite list .flat may return that infinite list, eating all your RAM in the process.

say ((1, 2), (3)).elems;        # 2
say ((1, 2), (3)).flat.elems;   # 3

method eager

Interprets the invocant as a list, evaluates it eagerly, and returns that list.

say (1..10).eager;              # 1 2 3 4 5 6 7 8 9 10

method elems

Interprets the invocant as a list, and returns the number of elements in the list.

say 42.elems;                   # 1
say <a b c>.elems;              # 3

method end

Interprets the invocant as a list, and returns the last index of that list.

say 6.end;                      # 0
say <a b c>.end;                # 2

method pairup

method pairup() returns List

Interprets the invocant as a list, and constructs a list of pairs from it, in the same way that assignment to a Hash does. That is, it takes two consecutive elements and constructs a pair from them, unless the item in the key position already is a pair (in which case the pair is passed is passed through, and the next list item, if any, is considered to be a key again).

say (a => 1, 'b', 'c').pairup.perl;     # ("a" => 1, "b" => "c").list

sub exit

sub exit(Int() $status = 0)

Exits the current process with return code $status.

Routines supplied by class Mu

Signature inherits from class Mu, which provides the following methods:

routine defined

multi sub    defined(Mu) returns Bool:D
multi method defined()   returns Bool:D

Returns False on the type object, and True otherwise.

say Int.defined;                # False
say 42.defined;                 # True

Very few types (like Failure) override defined to return False even for instances:

sub fails() { fail 'oh noe' };
say fails().defined;            # False

routine isa

multi method isa(Mu $type)      returns Bool:D
multi method isa(Str:D $type)   returns Bool:D

Returns True if the invocant is an instance of class $type, a subset type or a derived class (through inheritance) of $type.

my $i = 17;
say $i.isa("Int");   # True
say $i.isa(Any);     # True

A more idiomatic way to do this is to use the smartmatch operator ~~ instead.

my $s = "String";
say $s ~~ Str;       # True

routine Bool

multi sub    Bool(Mu) returns Bool:D
multi method Bool()   returns Bool:D

Returns False on the type object, and True otherwise.

Many built-in types override this to be False for empty collections, the empty string or numerical zeros

say Mu.Bool;                    # False
say;                # True
say [1, 2, 3].Bool;             # True
say [].Bool;                    # False
say { 'hash' => 'full'}.Bool;   # True
say {}.Bool;                    # False

method Str

multi method Str()   returns Str

Returns a string representation of the invocant, intended to be machine readable. Method Str warns on type objects, and produces the empty string.

say Mu.Str;                     #!> use of uninitialized value of type Mu in string context

routine gist

multi sub    gist(Mu) returns Str
multi method gist()   returns Str

Returns a string representation of the invocant, optimized for fast recognition by humans. As such lists will be truncated at 100 elements. Use .perl to get all elements.

The default gist method in Mu re-dispatches to the perl method for defined invocants, and returns the type name in parenthesis for type object invocants. Many built-in classes override the case of instances to something more specific that may truncate output.

gist is the method that say calls implicitly, so say $something and say $something.gist generally produce the same output.

say Mu.gist;        # (Mu)
say;    #

routine perl

multi sub    perl(Mu) returns Str
multi method perl()   returns Str

Returns a Perlish representation of the object (i.e., can usually be re-evaluated with EVAL to regenerate the object). The exact output of perl is implementation specific, since there are generally many ways to write a Perl expression that produces a particular value

method clone

method clone(*%twiddles)

Creates a shallow clone of the invocant. If named arguments are passed to it, their values are used in every place where an attribute name matches the name of a named argument.

class Point2D {
    has ($.x, $.y);
    multi method gist(Point2D:D:) {
        "Point($.x, $.y)";

my $p = => 2, y => 3);

say $p;                     # Point(2, 3)
say $p.clone(y => -5);      # Point(2, -5)

method new

multi method new(*%attrinit)

Default method for constructing (create + initialize) new objects of a class. This method expects only named arguments which are then used to initialize attributes with accessors of the same name.

Classes may provide their own new method to override this default.

new triggers an object construction mechanism that calls submethods named BUILD in each class of an inheritance hierarchy, if they exist. See the documentation on object construction for more information.

method bless

method bless(*%attrinit) returns Mu:D

Lower-level object construction method than new.

Creates a new object of the same type as the invocant, uses the named arguments to initialize attributes, and returns the created object.

You can use this method when writing custom constructors:

class Point {
    has $.x;
    has $.y;
    multi method new($x, $y) {
        self.bless(:$x, :$y);
my $p =, 1);

(Though each time you write a custom constructor, remember that it makes subclassing harder).

method CREATE

method CREATE() returns Mu:D

Allocates a new object of the same type as the invocant, without initializing any attributes.

say Mu.CREATE.defined;  # True

method print

multi method print() returns Bool:D

Prints value to $*OUT after stringification using .Str method without adding a newline at end.

"abc\n".print;          # abc␤

method put

multi method put() returns Bool:D

Prints value to $*OUT after stringification using .Str method adding a newline at end.

"abc".put;              # abc␤

method say

multi method say() returns Bool:D

Prints value to $*OUT after stringification using .gist method with newline at end. To produce machine readable output use .put.

say 42;                 # 42␤

method ACCEPTS

multi method ACCEPTS(Mu:U: $other)

ACCEPTS is the method that smart matching with the infix ~~ operator and given/when invokes on the right-hand side (the matcher).

The Mu:U multi performs a type check. Returns True if $other conforms to the invocant (which is always a type object or failure).

say 42 ~~ Mu;           # True
say 42 ~~ Int;          # True
say 42 ~~ Str;          # False

Note that there is no multi for defined invocants; this is to allow autothreading of junctions, which happens as a fallback mechanism when no direct candidate is available to dispatch to.

method WHICH

multi method WHICH() returns ObjAt:D

Returns an object of type ObjAt which uniquely identifies the object. Value types override this method which makes sure that two equivalent objects return the same return value from WHICH.

say 42.WHICH eq 42.WHICH;       # True

method WHERE

method WHERE() returns Int

Returns an Int representing the memory address of the object.

method WHY

multi method WHY()

Returns the attached Pod value. For instance,

    sub cast(Spell $s)
    #= Initiate a specified spell normally
    #= (do not use for class 7 spells)
    say &cast.WHY;


Initiate a specified spell normally (do not use for class 7 spells)

See the documentation specification for details about attaching Pod to variables, classes, functions, methods, etc.

trait is export

multi sub trait_mod:<is>(Mu:U \type, :$export!)

Marks a type as being exported, that is, available to external users.

my class SomeClass is export { }

A user of a module or class automatically gets all the symbols imported that are marked as is export.

See /language/modules#Exporting_and_Selective_Importing for more details.

method take

method take()

Takes the given item and passes it to the enclosing gather block.

#| randomly select numbers for lotto
my $num-selected-numbers = 6;
my $max-lotto-numbers = 49;
gather for ^$num-selected-numbers {
    take (1 .. $max-lotto-numbers).pick(1);
}.say;    #-> 32 22 1 17 32 9  (for example)

method so

method so()

Returns a Bool value representing the logical non-negation of an expression. One can use this method similarly to the English sentence: "If that is so, then do this thing". For instance,

my @args = <-a -e -b -v>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if $ {
    say "Verbose option detected in arguments";
} #-> Verbose option detected in arguments

method not

method not()

Returns a Bool value representing the logical negation of an expression. Thus it is the opposite of so.

my @args = <-a -e -b>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if $verbose-selected.not {
    say "Verbose option not present in arguments";
} #-> Verbose option not present in arguments

Since there is also a prefix version of not, the above code reads better like so:

my @args = <-a -e -b>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if not $verbose-selected {
    say "Verbose option not present in arguments";
} #-> Verbose option not present in arguments