class IO::Handle

Opened file or stream

class IO::Handle does IO { }


method get

Reads a single line from the input stream (usually the Standard Input or a file).

Read one line from the standard input:


Read one line from a file:

my $fh = open 'filename';
my $line = $fh.get;

method getc

Read a single character from the input stream or return Nil. The operation is blocking and the stream may be buffered.

method eof

Returns True if the read operations have exhausted the content of the file.

method lines

method lines($limit = Inf)

Return a lazy list of the file's lines read via get, limited to $limit lines. The new line separator (i.e., $* will be excluded.

my @data;
my $data-file = open 'readings.csv';
for $data-file.lines -> $line {

method words

method words($count = Inf)

Return a lazy list of the file's words (separated on whitespace), limited to $count words.

my %dict;
++%dict{$_} for $*IN.words;
say "Most common words: ", %dict.sort(*.value).reverse.[^5];

method split

multi method split(IO::Handle:D: :$close = False, :$COMB)
multi method split(IO::Handle:D: $splitter, :$close = False, :$COMB)

Returns a lazy list of strings found between the splitter, just like split on strings.

my $fh = open 'path/to/file', :r;
$fn.split(' ', close => True); # Returns file content split by a space and closes file;

method comb

multi method comb(IO::Handle:D: :$close = False)
multi method comb(IO::Handle:D: Int:D $size, :$close = False)
multi method comb(IO::Handle:D: $comber, :$close = False)

Returns a lazy list of strings combed from the handle, just like comb on strings.

my $fh = open 'path/to/file', :r;
$fn.comb(/A+/); # Comb file contents by a regex.


my $fh = open 'path/to/file', :r;
$fn.comb(3, close => True); # Comb file contents by 3 characters and close after.

method print

method print(*@text --> Bool)

Text writing; writes the given @text to the filehandle. See write to write bytes.

my $fh = open 'path/to/file', :w;
$fh.print("some text\n");

method print-nl

method print-nl(IO::Handle:D: --> True)

Writes a newline to the filehandle. The newline marker, which is stored in the attribute $.nl-out, defaults to \n unless another marker has been specified in the call to open.

my $fh = open 'path/to/file', :w, nl-out => "\r\n";
$fh.print("some text");
$fh.print-nl;                                        # \r\n

method printf

This method is mostly identical to the C library printf and sprintf functions. The only difference between the two functions is that sprintf returns a string while the printf function writes to a file. See sub sprintf for details about the Perl 6 $format implementation

Note that currently printf is not a method for IO::Handle, but its effect may be duplicated with a work-around using sub sprintf and methods print or say. For example:

my $fh = open 'path/to/file', :w;
$fh.print(sprintf("%d\n", 32));

The say method (see below) may be used for an automatic ending newline:

my $fh = open 'path/to/file', :w;
$fh.say(sprintf("%d", 32));

See sub sprintf for details about formatting and more examples.

method say

method say(IO::Handle:D: |)

This method is identical to print except that it stringifies its arguments by calling .gist on them and auto-appends a newline, with a call to print-nl, after the final argument.

my $fh = open 'path/to/file', :w;
$fh.say(, 4));        # 3+4i\n

method read

method read(IO::Handle:D: Int(Cool:D) $bytes --> Blob)

Binary reading; reads and returns up to $bytes bytes from the filehandle.

method readchars

method readchars(IO::Handle:D: Int(Cool:D) $chars --> Str)

Reading chars; reads and returns up to $chars chars (graphemes) from the filehandle.

method write

method write(IO::Handle:D: Blob:D $buf)

Binary writing; writes $buf to the filehandle. See print to write characters.

method seek

method seek(IO::Handle:D: Int:D $offset, SeekType:D $whence --> True)

Move the file pointer (that is, the position at which any subsequent read or write operations will begin,) to the byte position specified by $offset relative to the location specified by $whence which may be one of:

The beginning of the file.

The current position in the file.

The end of the file. Please note that you need to specify a negative offset if you want to position before the end of the file.

method tell

method tell(IO::Handle:D: --> Int)

Return the current position of the file pointer in bytes.

method slurp-rest

multi method slurp-rest(IO::Handle:D: :$bin!, :$close --> Buf)
multi method slurp-rest(IO::Handle:D: :$enc, :$close --> Str)

Returns the remaining content of the file from the current file position (which may have been set by previous reads or by seek.) If the adverb :bin is provided a Buf will be returned, otherwise the return value will be a Str with the optional encoding :enc. Specifying the adverb :close will cause the filehandle to be closed when the call has finished.

my $fh = open("content.txt");
my $line = $fh.get;
my $rest-of-file = $fh.slurp-rest(:close);

method Supply

multi method Supply(IO::Handle:D: :$size = 65536, :$bin --> Supply)

Returns a Supply that will emit the contents of the handle in chunks. The size of the chunks is determined by the optional :size named parameter and defaults to 64K. The optional :bin named parameter can be specified to indicate binary reading of the contents, rather than character based reading.

method path

For a handle opened on a file this returns the IO::Path that represents the file. For the standard I/O handles $*IN, $*OUT and $*ERR it returns a IO::Special object.


method close

Will close a previously opened filehandle.


method flush

Will flush the filehandle to disk.


method native-descriptor

method native-descriptor()

This returns a value that the operating system would understand as a "file descriptor" and is suitable for passing to a native function that requires a file descriptor as an argument such as fcntl or ioctl.

method opened

method opened(IO::Handle:D: --> Bool)

Returns True if the handle is open.

method t

method t(IO::Handle:D: --> Bool)

Returns True if the handle is opened to a tty.

Related roles and classes

See also the related role IO and the related class IO::Path.

Type graph

Type relations for IO::Handle
perl6-type-graph IO::Handle IO::Handle Any Any IO::Handle->Any IO IO IO::Handle->IO Mu Mu Any->Mu IO::Pipe IO::Pipe IO::Pipe->IO::Handle IO::ArgFiles IO::ArgFiles IO::ArgFiles->IO::Handle

Stand-alone image: vector, raster

Routines supplied by role IO

IO::Handle does role IO, which provides the following methods:

(IO) sub print

Print the given text on $*OUT (standard output), e.g.:

print "Hi there!\n";   # Hi there!

Note that the print function does not (in contrast to some other languages) append a newline character to the text. Thus the following code

print "Hi there!";
print "How are you?";
print (0..101).list;


Hi there!How are you?0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101

To print text implicitly including the trailing newline character, use say.

(IO) sub put

Print the given text on $*OUT (standard output) with appended $* The default for the latter is the platform dependent newline sequence.

put 'Merry 1.0!';
put (0..101).list;


Merry 1.0!␤
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

(IO) sub say

Print the given text in human readable form, followed by a $* (platform dependent newline) on $*OUT (standard output). Long output may be truncated. For machine readable output use put.

With say, the example code as mentioned in the print section will be displayed as the user likely intended:

say "Hi there!";
say "How are you?";
say (0..101).list;


Hi there!␤
How are you?␤
(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 ...)␤

say prints non-Str objects by calling their .gist method before printing. Hence the following say statements for the respective containers are equivalent:

my @array = qw{1 2 3 4};
say @array;       # [1 2 3 4]
say @array.gist;  # [1 2 3 4]

my %hash = "a" => 1, "b" => 2, "c" => 3;
say %hash;        # {a => 1, b => 2, c => 3}
say %hash.gist;   # {a => 1, b => 2, c => 3}

(IO) sub note

Print the given text, followed by a newline "\n" on $*ERR (standard error). Before printing, call the .gist method on any non-Str objects.

note is effectively say, only it writes its output to the standard error stream. For instance:

if ("path/to/pirate/treasure".IO.e) {
    say "Found pirate treasure!";
else {
    note "Could not find pirate treasure.  Are you sure it exists?";

will report (on the standard output stream) that treasure has been found if it exists or will note on the error stream that it couldn't be found if it doesn't exist.

(IO) sub dd

The Tiny Data Dumper. This function takes the input list of variables and notes them (on $*ERR) in an easy to read format, along with the name of the variable. Thus,

my $a = 42;
my %hash = "a" => 1, "b" => 2, "c" => 3;
dd %hash, $a;
# %hash = ("a" => 1, "c" => 3, "b" => 2).hash, $a = 42

to the standard error stream.

This is in spirit similar to Perl 5's Data::Dumper module.

Please note that dd will ignore named parameters. You can use a capture to force it to dump everything passed to it.

dd \((:a(1), :b(2)), :c(3));

If you don't specify any parameters at all, it will just print the type and name of the current subroutine / method to the standard error stream:

sub a { dd }; a    # sub a

This can be handy as a cheap trace function.

(IO) sub prompt

sub prompt($msg)

Prints $msg to standard output and waits for the user to type something and finish with an ENTER. Returns the string typed in without the trailing newline.

my $name = prompt("Hi, what's your name? ");

(IO) sub open

my $fh = open(IO::Path() $path, :$r, :$w, :$a, :$rw,
              :$bin, :$enc, :$nl, :$chomp)

Opens the $path (by default in text mode) with the given options, returning an IO::Handle object.

File mode options

  • read-only mode, :r

  • Open the file as read only, e.g.:

    my $fh = open("path/to/file", :r);

    This is the default mode for open.

    Write-related methods on the returned IO::Handle object will fail in this mode:

    my $fh = open("test");   # the file "test" already exists
    $fh.print("new text\n"); # fails
    CATCH { default { put .^name, ': ', .Str } };
    # OUTPUT: «X::AdHoc: Failed to write bytes to filehandle: bad file descriptor␤»
  • write-only mode, :w

  • Open the file for writing, creating it if it doesn't exist or overwriting the file if it does exist, e.g.:

    my $fh = open("path-to-file", :w);

    Read-related methods will fail in this mode:

    my $fh = open("test", :w);
    $fh.print("more stuff\n");
    $;      # return to the start of the file
    $fh.get();        # fails
    CATCH { default { put .^name, ': ', .Str } };
    # OUTPUT: «Reading from filehandle failed: bad file descriptor␤»
  • read-write mode, :rw

  • Open the file for reading and writing, creating the file if it doesn't exist or overwriting the file if it already exists.

    my $fh = open("path-to-file", :rw);
  • append mode, :a

  • Open the file for appending. If the file does not exist, create it. If the file already exists, append data to it.

    my $fh = open("path-to-file", :a);

    Encoding options

  • binary mode, :bin

  • Open the file in binary mode (byte mode):

    my $fh = open("path-to-file", :bin);

    A file opened with :bin may still be processed line-by-line, but IO will be in terms of Buf rather than Str types. Default is False, implying text semantics.

  • text mode encoding, :enc

  • The encoding to use if opened in text mode.

    # open explicitly as utf8
    my $fh = open("path-to-file", enc => "utf8");
    my $fh = open("path-to-file", enc => "utf-8");  # this form also works
    # open with latin1 encoding
    my $fh = open("path-to-file", enc => "latin1");

    Defaults to "Unicode", which implies figuring out which actual UTF is in use, either from a BOM or other heuristics. If heuristics are inconclusive, UTF-8 will be assumed. (No 8-bit encoding will ever be picked implicitly.) There exists no valid option with the name "Unicode", so the following will result in an error:

    my $fh = open("path-to-file", enc => "UTF-8");

    This is because one needs to specify a specific unicode encoding, e.g. "utf8".

    Newline options

  • end-of-line (EOL) marker, :nl

  • The marker used to indicate the end of a line of text. Only used in text mode. Defaults to "EOL", which implies accepting any combination of "\n", "\r\n" or "\r" or any other Unicode character that has the Zl (Separator, Line) property.

    # explicitly use CR-LF as EOL character
    my $fh = open("path-to-file", nl => "\r\n");
  • chomp mode, :chomp

  • Whether or not to remove newline characters from text obtained with .lines and .get. Defaults to True.

    # don't remove newline characters from input
    my $fh = open("path-to-file", chomp => False);
    say $fh.get();     # returns line including newline char

    (IO) method close

    To close an open file handle, simply call its close method:

    my $fh = open("path-to-file");
    # ... do stuff with the file

    It is also possible to call this as a sub, thus the example above can be written equivalently like so:

    my $fh = open("path-to-file");
    # ... do stuff with the file
    close $fh;

    When a file was opened for writing, closing it is important to ensure that all contents are actually written to the file. You may want to consider using a LEAVE phaser to guard against exceptions.

    (IO) sub slurp

    Slurps the contents of the entire file into a Str (or Buf if :bin). Accepts :bin and :enc optional named parameters, with the same meaning as open(). The routine will fail if the file does not exist, or is a directory.

    # read entire file as (Unicode) Str
    #my $text_contents   = slurp "path-to-file";
    # read entire file as Latin1 Str
    #my $text_contents   = slurp "path-to-file", enc => "latin1";
    # read entire file as Buf
    #my $binary_contents = slurp "path-to-file", :bin;

    (IO) sub spurt

    sub spurt($where, $what,
        Str  :$enc        = 'utf8',
        Bool :$bin        = False,
        Bool :$append      = False,
        Bool :$createonly = False,
        --> Bool ) is export

    Writes the indicated contents (2nd positional parameter, $what) to the location indicated by the first positional parameter, $where (which can either be a string or an IO::Path object). To write to an IO::Handle, use the print method.

    If a file needs to be opened for writing, it will also be closed. Returns True on success, or the appropriate Failure if something went wrong.

    These named parameters are optional and only have meaning if the first positional parameter was not an IO::Handle:


  • :enc

  • The encoding with which the contents will be written.

  • :bin

  • Open the file in binary mode.

  • :append

  • Boolean indicating whether to append to a (potentially) existing file. If the file did not exist yet, it will be created. Defaults to False.

  • :createonly

  • Boolean indicating whether to fail if the file already exists. Defaults to False.


    # write directly to a file
    #spurt "path/to/file", "default text, directly written";
    # write directly with a non-Unicode encoding
    #spurt "path/to/latin1_file", "latin1 text: äöüß", enc => "latin1";
    # append to a pre-existing file
    #spurt "file_already_exists", "some text";
    #spurt "file_already_exists", "new text", :append;
    #slurp "file_already_exists";   # some text␤new text
    # fail when writing to a pre-existing file
    #spurt "file_already_exists", "new text", :createonly;
    CATCH { default { put .^name, ': ', .Str } };
    # OUTPUT: «X::Cannot::Empty: Cannot pop from an empty Array␤»

    (IO) sub run

    sub run(*@args ($, *@)) returns Proc

    Runs an external command without involving a shell (if possible).

    See Proc for more details, for example on how to capture output.

    (IO) sub shell

    sub shell($cmd) returns Proc

    Runs a command through the system shell. All shell meta characters are interpreted by the shell, including pipes, redirects, environment variable substitutions and so on. See run if you don't want that.

    The return value is of type Proc.

    shell 'ls -lR | gzip -9 > ls-lR.gz';

    See Proc for more details, for example on how to capture output.

    Routines supplied by class Any

    IO::Handle inherits from class Any, which provides the following methods:

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

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


    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.


    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

    IO::Handle 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 ='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 ='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;                # 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) 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 = => 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 =, 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)
    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.

    (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 writable container to the invocant (see more details here: return-rw).

    (Mu) method take

    method take()

    Returns the invocant in the enclosing 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 $ {
        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