class IO::Special

Path to Special I/O device

class IO::Special does IO { }

Used as a $.path attribute in special standard input and output handles $*IN, $*OUT and $*ERR. Provides abridged interface of IO::Handle, mostly file tests and stringification.


method new

method new(:$!what!)

Takes a single required attribute what. It is unlikely that you will ever need to construct one of these objects yourself.

attribute what

say $*OUT.path.what# OUTPUT: «<STDOUT>␤» 

Returns one of the strings '<STDIN>', '<STDOUT>', or '<STDERR>', specifying the type of the special IO device.

method WHICH

method WHICH(IO::Special:D: --> Str)

This returns a string that identifies the object.

method Str

method Str(IO::Special:D:)

This returns '<STDIN>', '<STDOUT>', or '<STDERR>' as appropriate.

method IO

method IO(IO::Special:D: --> IO::Special)

Returns the invocant.

method e

method e(IO::Special:D: --> Bool)

The 'exists' file test operator, always returns True.

method d

method d(IO::Special:D: --> Bool)

The 'directory' file test operator, always returns False.

method f

method f(IO::Special:D: --> Bool)

The 'file' file test operator, always returns False.

method s

method s(IO::Special:D: --> Int)

The 'size' file test operator, always returns 0.

method l

method l(IO::Special:D: --> Bool)

The 'symbolic links' file test operator, always returns False.

method r

method r(IO::Special:D: --> Bool)

The 'read access' file test operator, returns True if this is the standard input handle, False otherwise.

method w

method w(IO::Special:D: --> Bool)

The 'write access' file test operator, returns True if this is the standard output or standard error handle, False if it is the standard input.

method x

method x(IO::Special:D: --> Bool)

The 'execute access' file test operator, always returns False.

method modified

method modified(IO::Special:D: --> Instant)

The last modified time always returns an Instant type object.

method accessed

method accessed(IO::Special:D: --> Instant)

The last accessed time always returns an Instant type object.

method changed

method changed(IO::Special:D: --> Instant)

The last changed time always returns an Instant type object.

method mode

method mode(IO::Special:D: --> Nil)

The mode always returns Nil

Type graph

Type relations for IO::Special
perl6-type-graph IO::Special IO::Special Any Any IO::Special->Any IO IO IO::Special->IO Mu Mu Any->Mu

Stand-alone image: vector

Routines supplied by role IO

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

(IO) sub chdir

Defined as:

sub chdir(IO() $path:$d = True:$r:$w:$x --> IO::Path:D)

Changes value of $*CWD variable to the provided $path, optionally ensuring the new path passes several file tests. NOTE: that this routine does NOT alter the process's current directory (see &*chdir).

Returns IO::Path representing new $*CWD on success. On failure, returns Failure and leaves $*CWD untouched. The $path can be any object with an IO method that returns an IO::Path object. The available file tests are:

  • :d — check .d returns True

  • :r — check .r returns True

  • :w — check .w returns True

  • :x — check .x returns True

  • By default, only :d test is performed.

        chdir         '/tmp'# change $*CWD to '/tmp' and check its .d is True 
        chdir :r:w'/tmp'# … check its .r and .w are True 
        chdir '/not-there';   # returns Failure 

    Note that the following construct is a mistake:

        # WRONG! DO NOT DO THIS! 
        my $*CWD = chdir '/tmp/';

    Use indir instead.

    (IO) sub &*chdir

    Defined as:

        PROCESS:<&chdir> = sub (IO() $path --> IO::Path:D)

    Changes value of $*CWD variable to the provided $path and sets the process's current directory to the value of $path.absolute. NOTE: that in most cases, you want to use chdir routine instead.

    Returns IO::Path representing new $*CWD on success. On failure, returns Failure and leaves $*CWD untouched. The $path can be any object with an IO method that returns an IO::Path object.

    Note that unlike regular chdir, there are no arguments to specify which file tests to perform.

        &*chdir('/tmp');  # change $*CWD and process's current directory to '/tmp' 
        &*chdir('/not-there'); # returns Failure 

    Note that the following construct is a mistake:

        # WRONG! DO NOT DO THIS! 
        my $*CWD = &*chdir('/tmp');

    Use the following, instead; or see indir if you do not need to change process's current directory:

        temp $*CWD;

    (IO) sub chmod

    sub chmod(Int() $mode*@filenames --> List)

    Coerces all @filenames to IO::Path and calls IO::Path.chmod with $mode on them. Returns a List containing a subset of @filenames for which chmod was successfully executed.

    chmod 0o755, <myfile1  myfile2># make two files executable by the owner 

    (IO) sub indir

    Defined as:

    sub indir(IO() $path&code:$d = True:$r:$w:$x --> Mu)

    Takes Callable &code and executes it after locally (to &code) changing $*CWD variable to $path, optionally ensuring the new path passes several file tests. NOTE: that this routine does NOT alter the process's current directory (see &*chdir). The $*CWD outside of the &code is not affected, even if &code explicitly assigns a new value to $*CWD.

    Returns the return value of &code on success. On failure to successfully change $*CWD, returns Failure. WARNING: keep in mind that lazily evaluated things might end up NOT having the $*CWD set by indir in their dynamic scope by the type they're actually evaluated. Either ensure the generators have their $*CWD set or eagerly evaluate them before returning the results from indir:

    say indir("/tmp"{
        gather { take ".".IO }
    }.CWD# OUTPUT: «(/home/camelia)␤» 
    say indir("/tmp"{
        eager gather { take ".".IO }
    }.CWD# OUTPUT: «(/tmp)␤» 
    say indir("/tmp"{
        my $cwd = $*CWD;
        gather { temp $*CWD = $cwdtake ".".IO }
    }.CWD# OUTPUT: «(/tmp)␤» 

    The routine's $path argument can be any object with an IO method that returns an IO::Path object. The available file tests are:

  • :d — check .d returns True

  • :r — check .r returns True

  • :w — check .w returns True

  • :x — check .x returns True

  • By default, only :d test is performed.

    say $*CWD;                   # OUTPUT: «"/home/camelia".IO␤» 
    indir '/tmp'{ say $*CWD }# OUTPUT: «"/tmp".IO␤» 
    say $*CWD;                   # OUTPUT: «"/home/camelia".IO␤» 
    indir '/not-there'{;};     # returns Failure; path does not exist 

    (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;       # OUTPUT: «[1 2 3 4]␤» 
    say @array.gist;  # OUTPUT: «[1 2 3 4]␤» 
    my %hash = "a" => 1"b" => 2"c" => 3;
    say %hash;        # OUTPUT: «{a => 1, b => 2, c => 3}␤» 
    say %hash.gist;   # OUTPUT: «{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 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,

    Opens the $path (by default in text mode) with the given options, returning an IO::Handle object. In order to close the IO::Handle one needs to call close explicitly or use a LEAVE phaser.

    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.

    my $fh1 = open 'path-to-file';                # default, utf-8 
    my $fh2 = open 'path-to-file':enc<latin-1># explicit, latin-1 

    Defaults to utf8. The values are case-insensitive. The available encodings vary by implementation and backend. On Rakudo MoarVM the following are supported:


    Implementation may choose to also provide support for aliases, e.g. Rakudo allows aliases latin-1 for iso-8859-1 encoding and dashed utf versions: utf-8 and utf-16.

    Newline options

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

  • nl-in is the marker used to indicate the end of a line of text. Only used in text mode. Defaults to ["\n", "\r\n"] and does not include "\r". nl-out defaults to "\n".

    # explicitly use CR-LF as EOL character 
    my $fh = open("path-to-file"nl-in => "\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) 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

    Defined as:

    multi spurt(IO() $path|c)

    The $path can be any object with an IO method that returns an IO::Path object. Calls IO::Path.spurt on the $path, forwarding any of the remaining arguments.


  • :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 ($*@) --> Proc)

    Runs an external command without involving a shell and returns a Proc object.

    run 'touch''>foo.txt';
    run Q:w{rm >foo.txt}# Another way to use run, using word quoting for the 
                          # arguments 

    To capture output you can use the :out argument:

    my $proc = run 'echo''Perl 6 is Great!':out;
    say $proc.out.get# OUTPUT: Perl 6 is Great! 

    See Proc and Proc::Async for more details.

    (IO) sub shell

    sub shell($cmd --> 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. Shell escapes are a severe security concern and can cause confusion with unusual file names. Use run if you want to be safe.

    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::Special 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(--> Junction:D)

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

    say so 2 == <1 2 3>.any;        # OUTPUT: «True␤» 
    say so 5 == <1 2 3>.any;        # OUTPUT: «False␤» 

    (Any) method all

    Defined as:

    method all(--> Junction:D)

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

    say so 1 < <2 3 4>.all;         # OUTPUT: «True␤» 
    say so 3 < <2 3 4>.all;         # OUTPUT: «False␤» 

    (Any) method one

    Defined as:

    method one(--> Junction:D)

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

    say so 1 == (123).one;      # OUTPUT: «True␤» 
    say so 1 == (121).one;      # OUTPUT: «False␤» 

    (Any) method none

    Defined as:

    method none(--> Junction:D)

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

    say so 1 == (123).none;     # OUTPUT: «False␤» 
    say so 4 == (123).none;     # OUTPUT: «True␤» 

    (Any) method list

    Defined as:

    method list(--> List:D)

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

    say 42.list.^name;           # OUTPUT: «List␤» 
    say 42.list.elems;           # OUTPUT: «1␤» 

    (Any) method push

    Defined as:

    method push(|values --> Positional:D)

    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 therefore 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  --> Seq:D)
    multi method reverse(List:D: --> Seq:D)

    Returns a Seq say reverse ^10; # OUTPUT: «(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;                           # OUTPUT: «(a b c)␤» 
    say 'bca'.comb.sort.join;                   # OUTPUT: «abc␤» 
    say 'bca'.comb.sort({$^b cmp $^a}).join;    # OUTPUT: «cba␤» 
    say '231'.comb.sort(&infix:«<=>»).join;     # OUTPUT: «123␤» 

    (Any) method map

    Defined as:

    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 --> Listis 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(&blockis 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

    Defined as:

    method flat(--> Seq:Dis nodal

    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 ((12), (3)).elems;        # OUTPUT: «2␤» 
    say ((12), (3)).flat.elems;   # OUTPUT: «3␤» 

    Please note that flat does not recurse 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]];
    say gather deepmap *.take@a# OUTPUT: «(1 2 3 4 5 6 7)␤» 

    (Any) method eager

    Defined as:

    method eager(--> Seq:Dis nodal

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

    say (1..10).eager;              # OUTPUT: «(1 2 3 4 5 6 7 8 9 10)␤» 

    (Any) method elems

    Defined as:

    method elems(--> Int:Dis nodal

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

    say 42.elems;                   # OUTPUT: «1␤» 
    say <a b c>.elems;              # OUTPUT: «3␤» 

    (Any) method end

    method end(--> Any:Dis nodal

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

    say 6.end;                      # OUTPUT: «0␤» 
    say <a b c>.end;                # OUTPUT: «2␤» 

    (Any) method pairup

    Defined as:

    method pairup(--> Seq:Dis nodal

    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 (=> 1'b''c').pairup.perl;     # OUTPUT: «(:a(1), :b("c")).Seq␤» 

    (Any) sub exit

    Defined as:

    sub exit(Int() $status = 0)

    Exits the current process with return code $status.

    (Any) sub item

    Defined as:

    proto sub item(|) is pure
    multi sub item(\x)
    multi sub item(|c)
    multi sub item(Mu $a)

    Forces given object to be evaluated in item context and returns the value of it.

    say item([1,2,3]).perl;              # OUTPUT: «$[1, 2, 3]␤» 
    say item({ apple => 10 }).perl;      # OUTPUT: «${:apple(10)}␤» 
    say item("abc").perl;                # OUTPUT: «"abc"␤» 

    You can also use $ as item contextualizer.

    say $[1,2,3].perl;                   # OUTPUT: «$[1, 2, 3]␤» 
    say $("abc").perl;                   # OUTPUT: «"abc"␤» 

    (Any) method Array

    Defined as:

    method Array(--> Array:Dis nodal

    Coerce the invocant to Array.

    (Any) method List

    Defined as:

    method List(--> List:Dis nodal

    Coerce the invocant to List.

    (Any) method Hash

    Defined as:

    method Hash(--> Hash:Dis nodal

    Coerce the invocant to Hash.

    (Any) method hash

    Defined as:

    method hash(--> Hash:Dis nodal

    Coerce the invocant to Hash.

    (Any) method Slip

    Defined as:

    method Slip(--> Slip:Dis nodal

    Coerce the invocant to Slip.

    (Any) method Map

    Defined as:

    method Map(--> Map:Dis nodal

    Coerce the invocant to Map.

    (Any) method Bag

    Defined as:

    method Bag(--> Bag:Dis nodal

    Coerce the invocant to Bag, whereby Positionals are treated as lists of values.

    (Any) method BagHash

    Defined as:

    method BagHash(--> BagHash:Dis nodal

    Coerce the invocant to BagHash, whereby Positionals are treated as lists of values.

    (Any) method Set

    Defined as:

    method Set(--> Set:Dis nodal

    Coerce the invocant to Set, whereby Positionals are treated as lists of values.

    (Any) method SetHash

    Defined as:

    method SetHash(--> SetHash:Dis nodal

    Coerce the invocant to SetHash, whereby Positionals are treated as lists of values.

    (Any) method Mix

    Defined as:

    method Mix(--> Mix:Dis nodal

    Coerce the invocant to Mix, whereby Positionals are treated as lists of values.

    (Any) method MixHash

    Defined as:

    method MixHash(--> MixHash:Dis nodal

    Coerce the invocant to MixHash, whereby Positionals are treated as lists of values.

    (Any) method Supply

    Defined as:

    method Supply(--> Supply:Dis nodal

    Coerce the invocant first to a List and then to a Supply.

    (Any) method min

    Defined As:

    multi method min(--> Any:D)
    multi method min(&by --> Any:D)

    Coerces to Iterable and returns the numerically smallest element. If a Callable is provided it is called with each element and its smallest return values is returned.

    (Any) method max

    Defined As:

    multi method max(--> Any:D)
    multi method min(&by --> Any:D)

    Coerces to Iterable and returns the numerically biggest element. If a Callable is provided it is called with each element and its biggest return values is returned.

    (Any) method minmax

    Defined As:

    multi method minmax(--> List:D)
    multi method minmax(&by --> List:D)

    Returns a list containing the smallest and the biggest element. If a Callable is provided each element is filtered and then numerically compared.


    (Any) method minpairs

    Defined As:

    multi method minpairs(Any:D: --> Seq:D)

    Calls .pairs and returns a Seq with all of the Pairs with minimum values, as judged by the cmp operator:

    <a b c a b c>.minpairs.perl.put# OUTPUT: «(0 => "a", 3 => "a").Seq␤» 
    %(:42a, :75b).minpairs.perl.put# OUTPUT: «(:a(42),).Seq␤» 

    (Any) method maxpairs

    Defined As:

    multi method maxpairs(Any:D: --> Seq:D)

    Calls .pairs and returns a Seq with all of the Pairs with maximum values, as judged by the cmp operator:

    <a b c a b c>.maxpairs.perl.put# OUTPUT: «(2 => "c", 5 => "c").Seq␤» 
    %(:42a, :75b).maxpairs.perl.put# OUTPUT: «(:b(75),).Seq␤» 

    (Any) method sum

    Defined As:

        method sum(--> TODO)


    (Any) method keys

    Defined As:

        method keys(--> TODO)


    (Any) method flatmap

    Defined As:

        method flatmap(--> TODO)


    (Any) method roll

    Defined As:

        method roll(--> TODO)


    (Any) method pick

    Defined As:

        method pick(--> TODO)


    (Any) method head

    Defined As:

        method head(--> TODO)


    (Any) method tail

    Defined As:

        method tail(--> TODO)


    (Any) method skip

    Defined As:

        method skip(--> TODO)


    (Any) method prepend

    Defined As:

        method prepend(--> TODO)


    (Any) method unshift

    Defined As:

        method unshift(--> TODO)


    (Any) method first

    Defined As:

        method first(--> TODO)


    (Any) method unique

    Defined As:

        method unique

    Treats the Any as a 1-item list and uses List.unique on it.

    (Any) method repeated

    Defined As:

        method repeated(--> TODO)


    (Any) method squish

    Defined As:

        method squish(--> TODO)


    (Any) method reduce

    Defined As:

        method reduce(--> TODO)


    (Any) method permutations

    Defined As:

        method permutations(--> TODO)


    (Any) method categorize

    Defined As:

        method categorize(--> TODO)


    (Any) method classify

    Defined As:

        method classify(--> TODO)


    (Any) method produce

    Defined As:

        method produce(--> TODO)


    (Any) method rotor

    Defined As:

        method rotor(--> TODO)


    (Any) method pairs

    Defined As:

        method pairs(--> TODO)


    (Any) method antipairs

    Defined As:

        method antipairs(--> TODO)


    (Any) method kv

    Defined As:

        method kv(--> TODO)


    (Any) method tree

    Defined As:

        method tree(--> TODO)


    (Any) method nl-out

    Defined As:

        method nl-out(--> TODO)


    (Any) method invert

    Defined As:

        method invert(--> TODO)


    (Any) method combinations

    Defined As:

        method combinations(--> TODO)


    (Any) method print-nl

    Defined As:

        method print-nl(--> TODO)


    (Any) method nodemap

    Defined As:

        method nodemap(--> TODO)


    (Any) method iterator

    Defined As:

        method iterator(--> TODO)


    (Any) method grep

    Defined As:

        method grep(--> TODO)


    (Any) method match

    Defined As:

        method match(--> TODO)


    (Any) method append

    Defined As:

        method append(--> TODO)


    (Any) method join

    Defined As:

        method join(--> TODO)


    (Any) method values

    Defined As:

        method values(--> TODO)


    (Any) method collate

    Defined As:

        method collate(--> TODO)


    (Any) method batch

    Defined As:

        method batch(--> TODO)


    (Any) method cache

    Defined As:

        method cache(--> TODO)


    Routines supplied by class Mu

    IO::Special inherits from class Mu, which provides the following methods:

    (Mu) routine defined

    multi sub    defined(Mu --> Bool:D)
    multi method defined(   --> Bool:D)

    Returns False on the type object, and True otherwise.

    say Int.defined;                # OUTPUT: «False␤» 
    say 42.defined;                 # OUTPUT: «True␤» 

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

    sub fails() { fail 'oh noe' };
    say fails().defined;            # OUTPUT: «False␤» 

    (Mu) routine isa

    multi method isa(Mu $type     --> Bool:D)
    multi method isa(Str:D $type  --> 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");   # OUTPUT: «True␤» 
    say $i.isa(Any);     # OUTPUT: «True␤» 

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

    my $s = "String";
    say $s ~~ Str;       # OUTPUT: «True␤» 

    (Mu) routine does

    method does(Mu $type --> 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;                # OUTPUT: «True␤» 
    say $d ~~ Any;                    # OUTPUT: «True␤» 
    say $d ~~ DateTime;               # OUTPUT: «False␤» 

    (Mu) routine Bool

    multi sub    Bool(Mu --> Bool:D)
    multi method Bool(   --> 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;                    # OUTPUT: «False␤» 
    say;                # OUTPUT: «True␤» 
    say [123].Bool;             # OUTPUT: «True␤» 
    say [].Bool;                    # OUTPUT: «False␤» 
    say { 'hash' => 'full' }.Bool;  # OUTPUT: «True␤» 
    say {}.Bool;                    # OUTPUT: «False␤» 
    say "".Bool;                    # OUTPUT: «False␤» 
    say 0.Bool;                     # OUTPUT: «False␤» 
    say 1.Bool;                     # OUTPUT: «True␤» 
    say "0".Bool;                   # OUTPUT: «True␤» 

    (Mu) method Str

    multi method Str(--> 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 --> Str)
    multi method gist(   --> 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;        # OUTPUT: «(Mu)␤» 
    say;    # OUTPUT: «␤» 

    (Mu) routine perl

    multi sub    perl(Mu --> Str)
    multi method perl(   --> 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 item

    method item(Mu \item:is raw

    Forces the invocant to be evaluated in item context and returns the value of it.

    say [1,2,3].item.perl;         # OUTPUT: «$[1, 2, 3]␤» 
    say { apple => 10 }.item.perl# OUTPUT: «${:apple(10)}␤» 
    say "abc".item.perl;           # OUTPUT: «"abc"␤» 

    (Mu) method self

    method self(--> Mu)

    Returns the object it is called on.

    (Mu) method clone

    method clone(*%twiddles)

    Creates a shallow clone of the invocant. Alternative values for public attributes can be provided via named arguments with names matching the attributes' names.

    class Point2D {
        has ($.x$.y);
        multi method gist(Point2D:D:{
    my $p = => 2=> 3);
    say $p;                     # OUTPUT: «Point(2, 3)␤» 
    say $p.clone(=> -5);      # OUTPUT: «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 --> 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{
    my $p =;

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

    (Mu) method CREATE

    method CREATE(--> Mu:D)

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

    say Mu.CREATE.defined;  # OUTPUT: «True␤» 

    (Mu) method print

    multi method print(--> Bool:D)

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

    "abc\n".print;          # RESULT: «abc␤» 

    (Mu) method put

    multi method put(--> Bool:D)

    Prints value to $*OUT, adding a newline at end, and if necessary, stringifying non-Str object using the .Str method.

    "abc".put;              # RESULT: «abc␤» 

    (Mu) method say

    multi method say(--> Bool:D)

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

    say 42;                 # OUTPUT: «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;           # OUTPUT: «True␤» 
    say 42 ~~ Int;          # OUTPUT: «True␤» 
    say 42 ~~ Str;          # OUTPUT: «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(--> 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;       # OUTPUT: «True␤» 

    (Mu) method WHERE

    method WHERE(--> 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 emit

    method emit()

    Emits the invocant into the enclosing supply or react block.

    react { whenever supply { .emit for "foo"42.5 } {
        say "received {.^name} ($_)";
    # OUTPUT: 
    # received Str (foo) 
    # received Int (42) 
    # received Rat (0.5) 

    (Mu) method take

    method take()

    Returns the invocant in the enclosing gather block.

    sub insert($sep+@list{
        gather for @list {
            FIRST .takenext;
            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;    # six random values 

    (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(@argseq '-v' | '-V';
    if $ {
        say "Verbose option detected in arguments";
    } # OUTPUT: «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(@argseq '-v' | '-V';
    if $verbose-selected.not {
        say "Verbose option not present in arguments";
    } # OUTPUT: «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(@argseq '-v' | '-V';
    if not $verbose-selected {
        say "Verbose option not present in arguments";
    } # OUTPUT: «Verbose option not present in arguments␤»