class Code

Code object

class Code is Any does Callable {}

Code is the ultimate base class of all code objects in Perl 6. It exposes functionality that all code objects have. While thunks are directly of type Code, most code objects (such as those resulting from blocks, subroutines or methods) will be of some subclass of Code.

Methods

method ACCEPTS

multi method ACCEPTS(Code:D: Mu $topic)

Usually calls the code object and passes $topic as an argument. However, when called on a code object that takes no arguments, the code object is invoked with no arguments and $topic is dropped. The result of the call is returned.

method arity

Defined as:

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

Returns the minimum number of positional arguments that must be passed in order to call the code object. Any optional or slurpy parameters in the code object's Signature do not contribute, nor do named parameters.

sub argless() { }
sub args($a, $b?) { }
sub slurpy($a, $b, *@c) { }
say &argless.arity;             # 0
say &args.arity;                # 1
say &slurpy.arity;              # 2

method count

Defined as:

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

Returns the maximum number of positional arguments that may be passed when calling the code object. For code objects that can accept any number of positional arguments (that is, they have a slurpy parameter), count will return Inf. Named parameters do not contribute.

sub argless() { }
sub args($a, $b?) { }
sub slurpy($a, $b, *@c) { }
say &argless.count;             # 0
say &args.count;                # 2
say &slurpy.count;              # Inf

of

Defined as:

method of(Code:D:) returns Mu

Returns the return type constraint of the Code:

m: say -> () --> Int {}.of
# OUTPUT: (Int)

method signature

Defined as:

multi method signature(Code:D:) returns Signature:D

Returns the Signature object for this code object, which describes its parameters.

sub a(Int $one, Str $two) {};
say &a.signature; # (Int $one, Str $two)

method Str

Defined as:

multi method Str(Code:D:) returns Str:D

Will produce a warning. Use .perl or .gist instead.

sub marine() { }
say ~&marine;    # marine
say &marine.Str; # marine

method file

Defined as:

method file(Code:D:) returns Str:D

Returns the name of the file in which the code object was declared.

say &infix:<+>.file;

method line

Defined as

method line(Code:D:) returns Int:D

Returns the line number in which the code object was declared.

say &infix:<+>.line;

Type graph

Type relations for Code
perl6-type-graph Code Code Any Any Code->Any Callable Callable Code->Callable Mu Mu Any->Mu WhateverCode WhateverCode WhateverCode->Code Block Block Block->Code Routine Routine Routine->Block Method Method Method->Routine Macro Macro Macro->Routine Sub Sub Sub->Routine Submethod Submethod Submethod->Routine Regex Regex Regex->Method

Stand-alone image: vector, raster

Routines supplied by role Callable

Code does role Callable, which provides the following methods:

(Callable) method CALL-ME

method CALL-ME(Callable:D $self: |arguments)

This method is required for postfix:«( )» and postfix:«.( )». It's what makes an object actually call-able and needs to be overloaded to let a given object act like a routine. If the object needs to be stored in a &-sigiled container, is has to implement Callable.

class A does Callable {
    submethod CALL-ME(|c){ 'called' }
}
my &a = A;
say a();
# OUTPUT«called␤»

(Callable) method assuming

method assuming(Callable:D $self: |primers)

Returns a Callable that implements the same behaviour as the original, but has the values passed to .assuming already bound to the corresponding parameters.

my sub slow($n){ my $i = 0; $i++ while $i < $n; $i };

# takes only one parameter and as such wont forward $n
sub bench(&c){ c, now - ENTER now };

say &slow.assuming(10000000).&bench;
# OUTPUT«(10000000 7.5508834)␤»

Routines supplied by class Any

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

(Any) method ACCEPTS

Defined as:

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

Usage:

EXPR.ACCEPTS(EXPR);

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

Many built-in types override this for more specific comparisons

(Any) 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

(Any) 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

(Any) 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

(Any) 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

(Any) method list

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

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

(Any) method push

The method push is defined for undefined invocants and allows 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 note the Array

(Any) 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.

Examples:

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

(Any) method sort

Sorts iterables with infix:<cmp> or given code object and returns a new List.

Examples:

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

(Any) 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.

The :$label and :$item are useful only internally, since for loops get converted to maps. The :$label takes an existing Label to label the .map's loop with and :$item controls whether the iteration will occur over (SELF,) (if :$item is set) or SELF.

(Any) method deepmap

Defined as:

method deepmap(&block -->List) is nodal

deepmap will apply &block to each element and return a new List with the return values of &block, unless the element does the Iterable role. For those elements deepmap will descend recursively into the sublist.

dd [[1,2,3],[[4,5],6,7]].deepmap(*+1);
# OUTPUT«[[2, 3, 4], [[5, 6], 7, 8]]␤»

(Any) method duckmap

Defined as:

method duckmap(&block) is rw is nodal

duckmap will apply &block on each element and return a new list with defined return values of the block. For undefined return values, duckmap will try to descend into the element if that element implements Iterable.

my @a = [1,[2,3],4];
dd @a.duckmap({ $_ ~~ Int ?? $_++ !! Any });
# OUTPUT«(1, (2, 3), 4)␤»

(Any) 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

Please not that flat is not recursing into sub lists. You have to recurse by hand or reconsider your data structures. A single level of nesting can often be handled with destructuring in signatures. For deeper structures you may consider gather/take to create a lazy list.

my @a = [[1,2,3],[[4,5],6,7]];
sub deepflat(@a){
    gather for @a {
        take ($_ ~~ Iterable ?? deepflat($_).Slip !! $_)
    }
};
dd deepflat(@a);
# OUTPUT«(1, 2, 3, 4, 5, 6, 7).Seq␤»

(Any) 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)

(Any) 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

(Any) 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

(Any) 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")).Seq

(Any) sub exit

sub exit(Int() $status = 0)

Exits the current process with return code $status.

Routines supplied by class Mu

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

(Mu) 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

(Mu) 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

(Mu) routine does

method does(Mu $type)      returns Bool:D

Returns True if and only if the invocant conforms to type $type.

my $d = Date.new('2016-06-03');
say $d.does(Dateish);             # True    (Date does role Dateish)
say $d.does(Any);                 # True    (Date is a subclass of Any)
say $d.does(DateTime);            # False   (Date is not a subclass of DateTime)

Using the smart match operator ~~ is a more idiomatic alternative.

my $d = Date.new('2016-06-03');
say $d ~~ Dateish;                # True
say $d ~~ Any;                    # True
say $d ~~ DateTime;               # False

(Mu) 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 Mu.new.Bool;                # True
say [1, 2, 3].Bool;             # True
say [].Bool;                    # False
say { 'hash' => 'full'}.Bool;   # True
say {}.Bool;                    # False

(Mu) 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

(Mu) 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 Mu.new.gist;    # Mu.new

(Mu) 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

(Mu) 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 = Point2D.new(x => 2, y => 3);

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

(Mu) 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.

(Mu) 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 = Point.new(-1, 1);

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

(Mu) 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

(Mu) 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␤

(Mu) 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␤

(Mu) 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␤

(Mu) 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.

(Mu) 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

(Mu) method WHERE

method WHERE() returns Int

Returns an Int representing the memory address of the object.

(Mu) 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)
{
do-raw-magic($s);
}
say &cast.WHY;

prints

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.

(Mu) 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 Exporting and Selective Importing Modules for more details.

(Mu) method return

method return()

The method return will stop execution of a subroutine or method, run all relevant phasers and provide invocant as a return value to the caller. If a return type constraint is provided it will be checked unless the return value is Nil. A control exception is raised and can be caught with CONTROL.

sub f { (1|2|3).return };
dd f(); # OUTPUT«any(1, 2, 3)␤»

(Mu) method return-rw

Same as method return except that return-rw returns a writeable container to the invocant (see more details here: return-rw).

(Mu) method take

method take()

Returns the invocant in the enlosing gather block.

sub insert($sep, +@list) {
    gather for @list {
        FIRST .take, next;
        take slip $sep, .item
    }
}

say insert ':', <a b c>;
# OUTPUT«(a : b : c)␤»

(Mu) routine take

sub take(\item)

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)

(Mu) routine take-rw

sub take-rw(\item)

Returns the given item to the enclosing gather block, without introducing a new container.

my @a = 1...3;
sub f(@list){ gather for @list { take-rw $_ } };
for f(@a) { $_++ };
say @a;
# OUTPUT«[2 3 4]␤»

(Mu) 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 $verbose-selected.so {
    say "Verbose option detected in arguments";
} #-> Verbose option detected in arguments

(Mu) 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