class IO::ArgFiles

Iterate over contents of files specified on command line

class IO::ArgFiles is IO::CatHandle { }

This class exists for backwards compatibility reasons and provides no methods. All the functionality is inherited from IO::CatHandle.

Variables

$*ARGFILES

This class is the magic behind the $*ARGFILES variable. This variable provides a way to iterate over files passed in to the program on the command line. Thus the examples above can be simplified like so:

use v6.c;
 
.say for $*ARGFILES.lines;
 
# or 
while ! $*ARGFILES.eof {
    say $*ARGFILES.get;
}
 
# or 
say $*ARGFILES.slurp;

Save one of the variations in a file, say argfiles.p6. Then create another file (named, say sonnet18.txt with the contents:

    Shall I compare thee to a summer's day?

Running the command

    $ perl6 argfiles.p6 sonnet18.txt

will then give the output

    Shall I compare thee to a summer's day?

Type graph

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

Stand-alone image: vector

Routines supplied by class IO::CatHandle

IO::ArgFiles inherits from class IO::CatHandle, which provides the following methods:

(IO::CatHandle) method new

Defined as:

method new(*@handles:&on-switch:$chomp = True:$nl-in = ["\n""\r\n"], Str :$encodingBool :$bin)

Creates a new IO::CatHandle object.

The @handles positional argument indicates a source of handles for the IO::CatHandle to read from and can a mixed collection of Cool, IO::Path, and IO::Handle (including IO::Pipe) objects. As input from IO::CatHandle is processed (so operations won't happen during .new call, but only when @handles' data is needed), it will walk through @handles list, processing each argument as follows: the Cool objects will be coerced to IO::Path; IO::Path objects will be opened for reading using the IO::CatHandle's (invocant's) attributes for open calls; un-opened IO::Handle objects will be opened in the same fashion as IO::Path objects; and already opened IO::Handle objects will have all of their attributes set to the attributes of the invocant IO::CatHandle. In short, all the @handles end up as IO::Handle objects opened in the same mode and with the same attributes as the invocant IO::CatHandle.

See .on-switch method for details on the :&on-switch named argument, which by default is not set.

The :$encoding specifies the handle's encoding and accepts the same values as IO::Handle.encoding. Set :$bin named argument to True if you wish the handle to be in binary mode. Attempting to specify both defined :$encoding and True :$bin is a fatal error resulting in X::IO::BinaryAndEncoding exception thrown. If :$encoding is not set and nor :$bin is not set to a true value, the handle will default to utf8 encoding.

The :$chomp and :$nl-in arguments have the same meaning as in IO::Handle and take and default to the same values.

(IO::CatHandle) method chomp

Defined as:

method chomp(IO::CatHandle:D:is rw

Sets the invocant's $.chomp attribute to the assigned value. All source handles, including the active one will use the provided $.chomp value.

    (my $f1 = 'foo'.IO).spurt: "A\nB\nC\n";
    (my $f2 = 'bar'.IO).spurt: "D\nE\n";
    with IO::CatHandle.new: $f1$f2 {
        # .chomp is True by default: 
        (.get xx 2).perl.say# OUTPUT: «("A", "B").Seq␤» 
 
        .chomp = False;
        (.get xx 3).perl.say# OUTPUT: «("C\n", "D\n", "E\n").Seq␤» 
        .close
    }

(IO::CatHandle) method nl-in

Defined as:

method nl-in(IO::CatHandle:D:is rw

Sets the invocant's $.nl-in attribute to the assigned value, which can be a Str or a List of Str, where each Str object represents the end-of-line string. All source handles, including the active one will use the provided $.nl-in value. Note that source handle boundary is always counted as a new line break.

    (my $f1 = 'foo'.IO).spurt: "A\nB\nC";
    (my $f2 = 'bar'.IO).spurt: "DxEx";
    with IO::CatHandle.new: $f1$f2 {
        # .nl-in is ["\n", "\r\n"] by default: 
        (.get xx 2).perl.say# OUTPUT: «("A", "B").Seq␤» 
 
        .nl-in = 'x';
        (.get xx 3).perl.say# OUTPUT: «("C", "D", "E").Seq␤» 
        .close
    }

(IO::CatHandle) method close

Defined as:

method close(IO::CatHandle:D: --> True)

Closes the currently active source handle, as well as any already-open source handles, and empties the source handle queue. Unlike a regular IO::Handle, an explicit call to .close is often not necessary on a CatHandle, as merely exhausting all the input closes all the handles that need to be closed.

    with IO::CatHandle.new: @bunch-of-handles {
        say .readchars: 42;
        .close# we are done; close all the open handles 
    }

(IO::CatHandle) method comb

Defined as:

method comb(IO::CatHandle:D: |args --> Seq:D)

Read the handle and processes its contents the same way Str.comb does, taking the same arguments. Implementations may slurp the contents of all the source handles in their entirety when this method is called.

    (my $f1 = 'foo'.IO).spurt: 'foo';
    (my $f2 = 'bar'.IO).spurt: 'bar';
    IO::CatHandle.new($f1$f2).comb(2).perl.say;
    # OUTPUT: «("fo", "ob", "ar").Seq␤» 

(IO::CatHandle) method DESTROY

Defined as:

method DESTROY(IO::CatHandle:D:)

Calls .close. This method isn't to be used directly, but is something that's called during garbage collection.

(IO::CatHandle) method encoding

Defined as:

multi method encoding(IO::CatHandle:D:)
multi method encoding(IO::CatHandle:D: $new-encoding)

Sets the invocant's $.encoding attribute to the provided value. Valid values are the same as those accepted by IO::Handle.encoding (use value Nil to switch to binary mode). All source handles, including the active one will use the provided $.encoding value.

    (my $f1 = 'foo'.IO).spurt: 'I ♥ Perl';
    (my $f2 = 'bar'.IO).spurt: 'meow';
    with IO::CatHandle.new: $f1$f2 {
        # .encoding is 'utf8' by default: 
        .readchars(5).say# OUTPUT: «I ♥ P␤» 
 
        .encoding: Nil# switch to binary mode 
        .slurp.say# OUTPUT: «Buf[uint8]:0x<72 6c 6d 65 6f 77>␤» 
    }

(IO::CatHandle) method eof

Defined as:

method eof(IO::CatHandle:D: --> Bool:D)

Returns True if the read operations have exhausted the source handle queue, including the contents of the last handle. Note: calling this method may cause one or more .on-switch calls, while the source handle queue is examined, and the source handle queue may get exhausted.

    (my $f1 = 'foo'.IO).spurt: 'foo';
    (my $f2 = 'bar'.IO).spurt: 'bar';
    with IO::CatHandle.new: :on-switch{ print 'SWITCH! ' }$f1$f2 {
                       # OUTPUT: «SWITCH! » 
        .eof.say;      # OUTPUT: «False␤» 
        .readchars(3);
        .eof.say;      # OUTPUT: «SWITCH! False␤» 
 
        .slurp;        # OUTPUT: «SWITCH! » 
        .eof.say;      # OUTPUT: «True␤» 
    }

(IO::CatHandle) method get

Defined as:

method get(IO::CatHandle:D: --> Bool:D)

Returns a single line of input from the handle, with the new line string defined by the value(s) of $.nl-in attribute, which will be removed from the line if $.chomp attribute attribute is set to True. Returns Nil when there is no more input. It is an error to call this method when the handle is in binary mode, resulting in X::IO::BinaryMode exception being thrown.

    (my $f1 = 'foo'.IO).spurt: "a\nb\nc";
    (my $f2 = 'bar'.IO).spurt: "d\ne";
    my $cat = IO::CatHandle.new: $f1$f2;
    .say while $_ = $cat.get# OUTPUT: «a␤b␤c␤d␤e␤» 

(IO::CatHandle) method getc

Defined as:

method getc(IO::CatHandle:D: --> Bool:D)

Returns a single character of input from the handle. All the caveats described in IO::Handle.getc apply. Returns Nil when there is no more input. It is an error to call this method when the handle is in binary mode, resulting in X::IO::BinaryMode exception being thrown.

    (my $f1 = 'foo'.IO).spurt: 'I ♥ Perl';
    (my $f2 = 'bar'.IO).spurt: 'meow';
    my $cat = IO::CatHandle.new: $f1$f2;
    .say while $_ = $cat.getc# OUTPUT: «I␤ ␤♥␤ ␤P␤e␤r␤l␤m␤e␤o␤w␤» 

(IO::CatHandle) method IO

Defined as:

method IO(IO::CatHandle:D:)

Alias for .path

(IO::CatHandle) method lines

Defined as:

method lines(IO::CatHandle:D: $limit = Inf:$close --> Seq:D)

Same as IO::Handle.lines. Note that a boundary between source handles is considered to be a newline break.

    (my $f1 = 'foo'.IO).spurt: "foo\nbar";
    (my $f2 = 'bar'.IO).spurt: 'meow';
    IO::CatHandle.new($f1$f2).lines.perl.say;
    # OUTPUT: «("foo", "bar", "meow").Seq␤» 

(IO::CatHandle) method lock

Defined as:

method lock(IO::CatHandle:D: Bool:D :$non-blocking = FalseBool:D :$shared = False --> True)

Same as IO::Handle.lock. Returns Nil if the source handle queue has been exhausted.

Locks only the currently active source handle. The .on-switch Callable can be used to conveniently lock/unlock the handles as they're being processed by the CatHandle.

(IO::CatHandle) method native-descriptor

Defined as:

method native-descriptor(IO::CatHandle:D: --> Int:D)

Returns the native-descriptor of the currently active source handle or Nil if the source handle queue has been exhausted.

Since the CatHandle closes a source handle, once it's done with it, it's possible for successive source handles to have the same native descriptor, if they were passed to .new as Cool or IO::Path objects.

    (my $f1 = 'foo'.IO).spurt: 'foo';
    (my $f2 = 'bar'.IO).spurt: 'bar';
    with IO::CatHandle.new: $f1$f2$*IN {
        repeat { .native-descriptor.say } while .next-handle;
        # OUTPUT: «13␤13␤9␤» 
    }

(IO::CatHandle) method next-handle

Defined as:

method next-handle(IO::CatHandle:D: --> IO::Handle:D)

Switches the active source handle to the next handle in the source handle queue, which is the sources given in @handles attribute to .new. The return value is the currently active source handle or Nil if the source handle queue has been exhausted.

Coerces Cool source "handles" to IO::Path; opens IO::Path and unopened IO::Handle source handles for reading using the invocant's $.nl-in, $.chomp, and $.encoding attributes; those same attributes of already-opened IO::Handle objects will be changed to the values of the invocant's attributes.

This method is called automatically whenever CatHandle's methods require a switch to the next source handle, triggers .on-switch Callable to be called, and is called once during .new call. The .on-switch will continue to be triggered each time this method is called, even after the source handle queue has been exhausted. Note that generally reaching the EOF of the currently active source handle does not trigger the .next-handle call, but rather further read operations that need more data do.

    (my $f1 = 'foo'.IO).spurt: "a\nb";
    (my $f2 = 'bar'.IO).spurt: "c\nd";
    with IO::CatHandle.new: :on-switch{ say '▸ Switching' }$f1$f2 {
        say 'one';
        .next-handle.^name.say;
        say 'two';
        .next-handle.^name.say;
        say 'three';
        .next-handle.^name.say;
        # OUTPUT: 
        # ▸ Switching 
        # one 
        # ▸ Switching 
        # IO::Handle 
        # two 
        # ▸ Switching 
        # Nil 
        # three 
        # ▸ Switching 
        # Nil 
    }

(IO::CatHandle) method on-switch

Defined as:

has &.on-switch is rw

One of the attributes that can be set during .new call and changed later by assigning to. By default is not specified. Takes a Callable with .count of 0, 1, 2, or Inf. Gets called each time .next-handle is called, which happens once during .new call and then each time a source handle is switched to the next one in the queue, or when the .next-handle method is called manually.

If the .count of &.on-switch is 0, it receives no arguments, if it's 1, it receives the currently active handle, and if it's 2 or Inf, it receives the currently active handle, and the last active handle as positional arguments (in that order). On the very first &.on-switch execution, the "last active handle" argument is Nil. Upon source handle queue exhaustion the "currently active handle" argument is Nil, and all the executions made afterwards have both arguments as Nil.

    (my $f1 = 'foo'.IO).spurt: "A\nB\nC";
    (my $f2 = 'bar'.IO).spurt: "D\nE";
 
    my $line;
    my $cat = IO::CatHandle.new: :on-switch{ $line = 1 }$f1$f2;
    say "{$cat.path}:{$line++} $_" for $cat.lines;
    # OUTPUT: 
    # foo:1 A 
    # foo:2 B 
    # foo:3 C 
    # bar:1 D 
    # bar:2 E 
    my @old-stuff;
    sub on-switch ($new$old{
        $new and $new.seek: 1SeekFromBeginning;
        $old and @old-stuff.push: $old.open.slurp: :close;
    }
 
    (my $f1 = 'foo'.IO).spurt: "A\nB\nC";
    (my $f2 = 'bar'.IO).spurt: "D\nE";
    my $cat = IO::CatHandle.new: :&on-switch$f1$f2;
    $cat.lines.perl.say# OUTPUT: «("", "B", "C", "", "E").Seq␤» 
    @old-stuff.perl.say# OUTPUT: «["A\nB\nC", "D\nE"]␤» 

(IO::CatHandle) method open

Defined as:

method open(IO::CatHandle:D: --> IO::CatHandle:D)

Returns the invocant. The intent of this method is to merely make CatHandle workable with things that open IO::Handle. You never have to call this method intentionally.

(IO::CatHandle) method opened

Defined as:

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

Returns True if the invocant has any source handles, False otherwise.

    say IO::CatHandle.new      .opened# OUTPUT: «False␤» 
    say IO::CatHandle.new($*IN).opened# OUTPUT: «True␤» 
 
    (my $f1 = 'foo'.IO).spurt: "A\nB\nC";
    with IO::CatHandle.new: $f1 {
        .opened.say# OUTPUT: «True␤» 
        .slurp;
        .opened.say# OUTPUT: «False␤» 
    }

(IO::CatHandle) method path

Defined as:

method path(IO::CatHandle:D:)

Returns the value of .path attribute of the currently active source handle, or Nil if the source handle queue has been exhausted. Basically, if your CatHandle is based on files, this is the way to get the path of the file the CatHandle is currently reading from.

    (my $f1 = 'foo'.IO).spurt: "A\nB\nC";
    (my $f2 = 'bar'.IO).spurt: "D\nE";
 
    my $line;
    my $cat = IO::CatHandle.new: :on-switch{ $line = 1 }$f1$f2;
    say "{$cat.path}:{$line++} $_" for $cat.lines;
    # OUTPUT: 
    # foo:1 A 
    # foo:2 B 
    # foo:3 C 
    # bar:1 D 
    # bar:2 E 

(IO::CatHandle) method read

Defined as:

method read(IO::CatHandle:D: Int(Cool:D$bytes = 65536 --> Buf:D)

Reads up to $bytes bytes from the handle and returns them in a Buf. $bytes defaults to an implementation-specific value (in Rakudo, the value of $*DEFAULT-READ-ELEMS, which by default is set to 65536). It is permitted to call this method on handles that are not in binary mode.

    (my $f1 = 'foo'.IO).spurt: 'meow';
    (my $f2 = 'bar'.IO).spurt: Blob.new: 456;
    with IO::CatHandle.new: :bin$f1$f2 {
        say .read: 2;    # OUTPUT: «Buf[uint8]:0x<6d 65>␤» 
        say .read: 2000# OUTPUT: «Buf[uint8]:0x<6f 77 04 05 06>␤» 
    }
 
    # Non-binary mode is OK too: 
    with IO::CatHandle.new: $f1$f2 {
        say .get;        # OUTPUT: «meow␤» 
        say .read: 2000# OUTPUT: «Buf[uint8]:0x<04 05 06>␤» 
    }

(IO::CatHandle) method readchars

Defined as:

method readchars(IO::CatHandle:D: Int(Cool:D$chars = 65536 --> Str:D)

Returns a Str of up to $chars characters read from the handle. $chars defaults to an implementation-specific value (in Rakudo, the value of $*DEFAULT-READ-ELEMS, which by default is set to 65536). It is NOT permitted to call this method on handles opened in binary mode and doing so will result in X::IO::BinaryMode exception being thrown.

    (my $f1 = 'foo'.IO).spurt: 'Perl loves to';
    (my $f2 = 'bar'.IO).spurt: ' meow';
 
    with IO::CatHandle.new: $f1$f2 {
        say .readchars: 11;   # OUTPUT: «Perl loves ␤» 
        say .readchars: 1000# OUTPUT: «to meow␤» 
    }

(IO::CatHandle) method seek

Defined as:

method seek(IO::CatHandle:D: |c)

Calls .seek on the currently active source handle, forwarding it all the arguments, and returns the result. Returns Nil if the source handle queue has been exhausted. NOTE: this method does NOT perform any source handle switching, so seeking past the end of the current source handle will NOT seek to the next source handle in the queue and seeking past the beginning of the current source handle is a fatal error. Also see .next-handle, to learn the details on when source handles are switched.

    (my $f1 = 'foo'.IO).spurt: 'foo';
    (my $f2 = 'bar'.IO).spurt: 'bar';
 
    with IO::CatHandle.new: $f1$f2 {
        .get.say;                     # OUTPUT: «foo␤» 
        .seek: -2SeekFromCurrent;
        .readchars(2).say;            # OUTPUT: «oo␤» 
        .seek: 1000SeekFromCurrent# this doesn't switch to second handle! 
        .readchars(3).say;            # OUTPUT: «bar␤» 
        try .seek: -4;                # this won't seek to previous handle! 
        say ~$!;                      # OUTPUT: «Failed to seek in filehandle: 22␤» 
    }

(IO::CatHandle) method tell

Defined as:

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

Calls .tell on the currently active source handle and returns the result. Returns Nil if the source handle queue has been exhausted.

    (my $f1 = 'foo'.IO).spurt: 'foo';
    (my $f2 = 'bar'.IO).spurt: 'bar';
 
    with IO::CatHandle.new: $f1$f2 {
        .get.say;                   # OUTPUT: «foo␤» 
        .tell.say;                  # OUTPUT: «3␤» 
        .seek: -2SeekFromCurrent;
        .tell.say;                  # OUTPUT: «1␤» 
        say .readchars: 3;          # OUTPUT: «oob␤» 
         .tell.say;                 # OUTPUT: «2␤» 
    }

(IO::CatHandle) method slurp

Defined as:

method slurp(IO::CatHandle:D:)

Reads all of the available input from all the source handles and returns it as a Buf if the handle is in binary mode or as a Str otherwise. Returns Nil if the source handle queue has been exhausted.

    (my $f1 = 'foo'.IO).spurt: 'foo';
    (my $f2 = 'bar'.IO).spurt: 'bar';
 
    IO::CatHandle.new(      $f1$f2).slurp.say# OUTPUT: «foobar␤» 
    IO::CatHandle.new(:bin$f1$f2).slurp.say# OUTPUT: «Buf[uint8]:0x<66 6f 6f 62 61 72>␤» 
    IO::CatHandle.new                .slurp.say# OUTPUT: «Nil␤» 

(IO::CatHandle) method split

Defined as:

method split(IO::CatHandle:D: |args --> Seq:D)

Read the handle and processes its contents the same way Str.split does, taking the same arguments. Implementations may slurp the contents of all the source handles in their entirety when this method is called.

    (my $f1 = 'foo'.IO).spurt: 'foo';
    (my $f2 = 'bar'.IO).spurt: 'bar';
    IO::CatHandle.new($f1$f2).split(/o+/).perl.say;
    # OUTPUT: «("f", "bar").Seq␤» 

(IO::CatHandle) method Str

Defined as:

method Str(IO::CatHandle:D: --> Str:D)

Calls .Str on the currently active source handle and returns the result. If the source handle queue has been exhausted, returns an implementation-defined string ('<closed IO::CatHandle>' in Rakudo).

(IO::CatHandle) method Supply

Defined as:

method Supply(IO::CatHandle:D: :$size = 65536 --> Supply:D)

Returns a Supply fed with either .read, if the handle is in binary mode, or with .readchars, if it isn't, with reads of :$size bytes or characters. :$size defaults to an implementation-specific value (in Rakudo, the value of $*DEFAULT-READ-ELEMS, which by default is set to 65536).

    (my $f1 = 'foo'.IO).spurt: 'foo';
    (my $f2 = 'bar'.IO).spurt: 'bar';
    react whenever IO::CatHandle.new($f1$f2).Supply: :2size {.say}
    # OUTPUT: «fo␤ob␤ar␤» 
 
    react whenever IO::CatHandle.new(:bin$f1$f2).Supply: :2size {.say}
    # OUTPUT: «Buf[uint8]:0x<66 6f>␤Buf[uint8]:0x<6f 62>␤Buf[uint8]:0x<61 72>␤» 

(IO::CatHandle) method t

Defined as:

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

Calls .t (tells if the handle is a TTY) on the currently active source handle and returns the result. If the source handle queue has been exhausted, returns False.

    (my $f1 = 'foo'.IO).spurt: 'foo';
    with IO::CatHandle.new: $f1$*IN {
        repeat { .t.say } while .next-handle# OUTPUT: «False␤True␤» 
    }

(IO::CatHandle) method unlock

Defined as:

method unlock(IO::CatHandle:D:)

Same as IO::Handle.unlock. Returns Nil if the source handle queue has been exhausted.

Unlocks only the currently active source handle. The .on-switch Callable can be used to conveniently lock/unlock the handles as they're being processed by the CatHandle.

(IO::CatHandle) method words

Defined as:

method words(IO::CatHandle:D: $limit = Inf:$close --> Seq:D)

Same as IO::Handle.words (including the caveat about more data read than needed to make some number of words). Note that a boundary between source handles is considered to be word boundary.

    (my $f1 = 'foo'.IO).spurt: 'foo bar';
    (my $f2 = 'bar'.IO).spurt: 'meow';
    IO::CatHandle.new($f1$f2).words.perl.say;
    # OUTPUT: «("foo", "bar", "meow").Seq␤» 

(IO::CatHandle) method flush

Defined as:

multi method flush(|)

In Rakudo, the IO::CatHandle type overrides this method to throw X::NYI exception. If you have a good idea for how this method should behave, tell Rakudo developers about it!

(IO::CatHandle) method nl-out

Defined as:

multi method nl-out(|)

In Rakudo, the IO::CatHandle type overrides this method to throw X::NYI exception. If you have a good idea for how this method should behave, tell Rakudo developers about it!

(IO::CatHandle) method print

Defined as:

multi method print(|)

In Rakudo, the IO::CatHandle type overrides this method to throw X::NYI exception. If you have a good idea for how this method should behave, tell Rakudo developers about it!

(IO::CatHandle) method printf

Defined as:

multi method printf(|)

In Rakudo, the IO::CatHandle type overrides this method to throw X::NYI exception. If you have a good idea for how this method should behave, tell Rakudo developers about it!

(IO::CatHandle) method print-nl

Defined as:

multi method print-nl(|)

In Rakudo, the IO::CatHandle type overrides this method to throw X::NYI exception. If you have a good idea for how this method should behave, tell Rakudo developers about it!

(IO::CatHandle) method put

Defined as:

multi method put(|)

In Rakudo, the IO::CatHandle type overrides this method to throw X::NYI exception. If you have a good idea for how this method should behave, tell Rakudo developers about it!

(IO::CatHandle) method say

Defined as:

multi method say(|)

In Rakudo, the IO::CatHandle type overrides this method to throw X::NYI exception. If you have a good idea for how this method should behave, tell Rakudo developers about it!

(IO::CatHandle) method write

Defined as:

multi method write(|)

In Rakudo, the IO::CatHandle type overrides this method to throw X::NYI exception. If you have a good idea for how this method should behave, tell Rakudo developers about it!

Routines supplied by class IO::Handle

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

(IO::Handle) method open

Defined as:

    method open(IO::Handle:D:
        :$bin:$enc:$chomp:$nl-inStr:D :$nl-out,
        Str :$mode,
        :$r:$w:$a:$x:$update:$rw:$rx:$ra,
        :$create:$append:$truncate:$exclusive,
        --> IO::Handle:D
    )

Opens the handle in one of the modes. Fails with appropriate exception if the open fails.

See description of individual methods for the accepted values and behaviour of :$chomp, :$nl-in, :$nl-out, and :$enc. The values for parameters default to the invocant's attributes and if any of them are provided, the attributes will be updated to the new values. Specify :$bin set to True instead of :$enc to indicate the handle should be opened in binary mode. Specifying undefined value as :$enc is equivalent to not specifying :$enc at all. Specifying both a defined encoding as :$enc and :$bin set to true will cause X::IO::BinaryAndEncoding exception to be thrown.

The open mode defaults to non-exclusive, read only (same as specifying :r) and can be controlled by a mix of the following arguments:

    :r      same as specifying   :mode<ro>
 
    :w      same as specifying   :mode<wo>:create:truncate
    :a      same as specifying   :mode<wo>:create:append
    :x      same as specifying   :mode<wo>:create:exclusive
 
    :update same as specifying   :mode<rw>
    :rw     same as specifying   :mode<rw>:create
    :ra     same as specifying   :mode<rw>:create:append
    :rx     same as specifying   :mode<rw>:create:exclusive

Support for combinations of modes other than what is listed above is implementation-dependent and should be assumed unsupported. That is, specifying, for example, .open(:r :create) or .open(:mode<wo> :append :truncate) might work or might cause the Universe to implode, depending on a particular implementation.

The mode details are:

    :mode<ro>  means "read only"
    :mode<wo>  means "write only"
    :mode<rw>  means "read and write"
 
    :create    means the file will be createdif it does not exist
    :truncate  means the file will be emptiedif it exists
    :exclusive means .open will fail if the file already exists
    :append    means writes will be done at the end of file's current contents

Attempts to open a directory, write to a handle opened in read-only mode or read from a handle opened in write-only mode, or using text-reading methods on a handle opened in binary mode will fail or throw.

Note: unlike some other languages, Perl 6 does not use reference counting, and so the file handles are NOT closed when they go out of scope. While they will get closed when garbage collected, garbage collection isn't guaranteed to get run. This means you must use an explicit close on handles opened for writing, to avoid data loss, and an explicit close is recommended on handles opened for reading as well, so that your program does not open too many files at the same time, triggering exceptions on further open calls.

(IO::Handle) method comb

Defined as:

method comb(IO::Handle:D: Bool :$close|args --> Seq:D)

Read the handle and processes its contents the same way Str.comb does, taking the same arguments, closing the handle when done if $close is set to a true value. Implementations may slurp the file in its entirety when this method is called.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

my $fh = 'path/to/file'.IO.open;
say "The file has {+$fh.comb: '':close} ♥s in it";

(IO::Handle) method chomp

Defined as:

has $.chomp is rw = True

One of the attributes that can be set via .new or open. Defaults to True. Takes a Bool specifying whether the line separators (as defined by .nl-in) should be removed from content when using .get or .lines methods.

(IO::Handle) routine get

Defined as:

method get(IO::Handle:D: --> Str:D)
multi sub get (IO::Handle $fh = $*ARGFILES --> Str:D)

Reads a single line of input from the handle, removing the trailing newline characters (as set by .nl-in) if the handle's .chomp attribute is set to True. Returns Nil, if no more input as available. The subroutine form defaults to $*ARGFILES if no handle is given.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

    $*IN.get.say;              # Read one line from the standard input 
 
    my $fh = open 'filename';
    $fh.get.say;               # Read one line from a file 
    $fh.close;
 
    say get;                   # Read one line from $*ARGFILES 

(IO::Handle) routine getc

Defined as:

method getc(IO::Handle:D: --> Str:D)
multi sub getc (IO::Handle $fh = $*ARGFILES --> Str:D)

Reads a single character from the input stream. Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown. The subroutine form defaults to $*ARGFILES if no handle is given. Returns Nil, if no more input as available, otherwise operation will block, waiting for at least one character to be available; these caveats apply:

Buffering terminals

Using getc to get a single keypress from a terminal will only work properly if you've set the terminal to "unbuffered". Otherwise the terminal will wait for the return key to be struck or the buffer to be filled up before perl6 gets even a single byte of data.

Waiting for potential combiners

If your handle's encoding allows combining characters to be read, perl6 will wait for more data to be available before it provides a character. This means that inputting an "e" followed by a combining acute will give you an e with an acute rather than giving an "e" and letting the next reading function give you a dangling combiner. However, it also means that when the user inputs just an "e" and has no intention to also input a combining acute, your program will be waiting for another keypress before the initial "e" is returned.

(IO::Handle) method eof

Defined as:

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

Returns True if the read operations have exhausted the contents of the handle.

(IO::Handle) method encoding

Defined as:

multi method encoding(IO::Handle:D: --> Str:D)
multi method encoding(IO::Handle:D: $enc --> Str:D)

Returns a Str representing the encoding currently used by the handle, defaulting to "utf8". Nil indicates the file handle is currently in binary mode. Specifying an optional positional $enc argument switches the encoding used by the handle; specify Nil as encoding to put the handle into binary mode.

The accepted values for encoding are case-insensitive. The available encodings vary by implementation and backend. On Rakudo MoarVM the following are supported:

  utf8
  utf16
  utf8-c8
  iso-8859-1
  windows-1252
  ascii

The default encoding is utf8, which undergoes normalization into Unicode NFC (normalization form canonical). In some cases you may want to ensure no normalization is done; for this you can use utf8-c8. Before using utf8-c8 please read Unicode: File Handles and I/O for more information on utf8-c8 and NFC.

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.

    with 'foo'.IO {
        .spurt: "First line is text, then:\nBinary";
        my $fh will leave {.close} = .open;
        $fh.get.say;         # OUTPUT: «First line is text, then:␤» 
        $fh.encoding: Nil;
        $fh.slurp.say;       # OUTPUT: «Buf[uint8]:0x<42 69 6e 61 72 79>␤» 
    }

(IO::Handle) routine lines

Defined as:

sub lines(IO::Handle:D $fh = $*ARGFILES$limit = Inf:$close --> Seq:D)
method lines(IO::Handle:D:               $limit = Inf:$close --> Seq:D)

Return a Seq each element of which is a line from the handle (that is chunks delineated by .nl-in). If the handle's .chomp attribute is set to True, then characters specified by .nl-in will be stripped from each line.

Reads up to $limit lines, where $limit can be a non-negative Int, Inf, or Whatever (which is interpreted to mean Inf). If :$close is set to True, will close the handle when the file ends or $limit is reached. Subroutine form defaults to $*ARGFILES, if no handle is provided.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

NOTE: the lines are read lazily, so ensure the returned Seq is either fully reified or is no longer needed when you close the handle or attempt to use any other methods that change the file position.

    say "The file contains ",
      '50GB-file'.IO.open.lines.grep(*.contains: 'Perl').elems,
      " lines that mention Perl";
    # OUTPUT: «The file contains 72 lines that mention Perl␤» 

(IO::Handle) method lock

Defined as:

method lock(IO::Handle:D: Bool:D :$non-blocking = FalseBool:D :$shared = False --> True)

Places an advisory lock on the filehandle. If :$non-blocking is True will fail with X::IO::Lock if lock could not be obtained, otherwise will block until the lock can be placed. If :$shared is True will place a shared (read) lock, otherwise will place an exclusive (write) lock. On success, returns True; fails with X::IO::Lock if lock cannot be placed (e.g. when trying to place a shared lock on a filehandle opened in write mode or trying to place an exclusive lock on a filehandle opened in read mode).

You can use lock again to replace an existing lock with another one. Use close the filehandle or use unlock to remove a lock.

# One program writes, the other reads, and thanks to locks either 
# will wait for the other to finish before proceeding to read/write 
 
# Writer 
given "foo".IO.open(:w{
    .lock;
    .spurt: "I ♥ Perl 6!";
    .close;
}
 
# Reader 
given "foo".IO.open {
    .lock: :shared;
    .slurp.say# OUTPUT: «I ♥ Perl 6!␤» 
    .close;
}

(IO::Handle) method unlock

Defined as:

method unlock(IO::Handle:D: --> True)

Removes a lock from the filehandle.

(IO::Handle) routine words

Defined as:

multi sub words(IO::Handle:D $fh = $*ARGFILES$limit = Inf:$close --> Seq:D)
multi method words(IO::Handle:D: $limit = Inf:$close --> Seq:D)

Similar to Str.words, separates the handle's stream on contiguous chunks of whitespace (as defined by Unicode) and returns a Seq of the resultant "words." Takes an optional $limit argument that can be a non-negative Int, Inf, or Whatever (which is interpreted to mean Inf), to indicate only up-to $limit words must be returned. If Bool :$close named argument is set to True, will automatically close the handle when the returned Seq is exhausted. Subroutine form defaults to $*ARGFILES, if no handle is provided.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

my %dict := bag $*IN.words;
say "Most common words: "%dict.sort(-*.value).head: 5;

NOTE: implementations may read more data than necessary when a call to .words is made. That is, $handle.words(2) may read more data than two "words" worth of data and subsequent calls to read methods might not read from the place right after the two fetched words. After a call to .words, the file position should be treated as undefined.

(IO::Handle) method split

Defined as:

method split(IO::Handle:D: :$close|c)

Slurps the handle's content and calls Str.split on it, forwarding any of the given arguments. If :$close named parameter is set to True, will close the invocant after slurping.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

my $fh = 'path/to/file'.IO.open;
$fh.split: '':close# Returns file content split on ♥ 

(IO::Handle) method spurt

Defined as:

multi method spurt(IO::Handle:D: Blob $data:$close = False)
multi method spurt(IO::Handle:D: Cool $data:$close = False)

Writes all of the $data into the filehandle, closing it when finished, if $close is True. For Cool $data, will use the encoding the handle is set to use (IO::Handle.open or IO::Handle.encoding).

Behaviour for spurting a Cool when the handle is in binary mode or spurting a Blob when the handle is NOT in binary mode is undefined.

(IO::Handle) method print

Defined as:

multi method print(**@text --> True)

Writes the given @text to the handle, coercing any non-Str objects to Str by calling .Str method on them. See write to write bytes.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

my $fh = 'path/to/file'.IO.open: :w;
$fh.print: 'some text';
$fh.close;

(IO::Handle) method print-nl

Defined as:

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

Writes the value of $.nl-out attribute into the handle.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

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

(IO::Handle) method printf

Defined as:

method printf(IO::Handle:D: Cool $format*@args)

Formats a string based on the given format and arguments and .prints the result into the filehandle. See sub sprintf for details on acceptable format directives.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

my $fh = open 'path/to/file':w;
$fh.printf: "The value is %d\n"32;
$fh.close;

(IO::Handle) method put

Defined as:

multi method put(**@text --> True)

Writes the given @text to the handle, coercing any non-Str objects to Str by calling .Str method on them, and appending the value of .nl-out at the end.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

my $fh = 'path/to/file'.IO.open: :w;
$fh.print: 'some text';
$fh.close;

(IO::Handle) method say

Defined as:

multi method say(IO::Handle:D: **@text --> True)

This method is identical to put except that it stringifies its arguments by calling .gist instead of .Str.

Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

my $fh = open 'path/to/file':w;
$fh.say(Complex.new(34));        # RESULT: «3+4i\n» 
$fh.close;

(IO::Handle) method read

Defined as:

method read(IO::Handle:D: Int(Cool:D$bytes = 65536 --> Buf:D)

Binary reading; reads and returns up to $bytes bytes from the filehandle. $bytes defaults to an implementation-specific value (in Rakudo, the value of $*DEFAULT-READ-ELEMS, which by default is set to 65536). This method can be called even when the handle is not in binary mode.

    (my $file = 'foo'.IO).spurt: 'I ♥ Perl';
    given $file.open {
        say .read: 6# OUTPUT: «Buf[uint8]:0x<49 20 e2 99 a5 20>␤» 
        .close;
    }

(IO::Handle) method readchars

Defined as:

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

Reading chars; reads and returns up to $chars chars (graphemes) from the filehandle. $chars defaults to an implementation-specific value (in Rakudo, the value of $*DEFAULT-READ-ELEMS, which by default is set to 65536). Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode exception being thrown.

    (my $file = 'foo'.IO).spurt: 'I ♥ Perl';
    given $file.open {
        say .readchars: 5# OUTPUT: «I ♥ P␤» 
        .close;
    }

(IO::Handle) method write

Defined as:

method write(IO::Handle:D: Blob:D $buf --> True)

Writes $buf to the filehandle. This method can be called even when the handle is not in binary mode.

(IO::Handle) method seek

Defined as:

method seek(IO::Handle:D: Int:D $offsetSeekType: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:

  • SeekFromBeginning

  • The beginning of the file.

  • SeekFromCurrent

  • The current position in the file.

  • SeekFromEnd

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

    (IO::Handle) method tell

    Defined as:

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

    Return the current position of the file pointer in bytes.

    (IO::Handle) method slurp-rest

    Defined as:

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

    DEPRECATION NOTICE: this method will be deprecated in 6.d language. Do not use it for new code. Use .slurp method method instead.

    Return 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 will be a Str with the optional encoding :enc.

    (IO::Handle) method slurp

    Defined as:

    method slurp(IO::Handle:D: :$close = False)

    Returns all the content from the current file position to the end. If the invocant is in binary mode, will return Buf, otherwise will decode the content using invocant's current .encoding and return a Str.

    If :$close is set to True, will close the handle when finished reading.

    (IO::Handle) method Supply

    Defined as:

    multi method Supply(IO::Handle:D: :$size = 65536)

    Returns a Supply that will emit the contents of the handle in chunks. The chunks will be Buf if the handle is in binary mode or, if it isn't, Str decoded using same encoding as IO::Handle.encoding.

    The size of the chunks is determined by the optional :size named parameter and 65536 bytes in binary mode or 65536 characters in non-binary mode.

        "foo".IO.open(:bin).Supply(:size<10>).tap: *.perl.say;
        # OUTPUT: 
        # Buf[uint8].new(73,32,226,153,165,32,80,101,114,108) 
        # Buf[uint8].new(32,54,33,10) 
    "foo".IO.open.Supply(:size<10>).tap: *.perl.say;
    # OUTPUT: 
    # "I ♥ Perl 6" 
    # "!\n" 

    (IO::Handle) method path

    Defined as:

    method path(IO::Handle:D:)

    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 an IO::Special object.

    (IO::Handle) method IO

    Defined as:

    method IO(IO::Handle:D:)

    Alias for .path

    (IO::Handle) method Str

    Returns the value of .path, coerced to Str.

        say "foo".IO.open.path# OUTPUT: «"foo".IO␤» 

    (IO::Handle) routine close

    Defined as:

    method close(IO::Handle:D: --> Bool:D)
    multi sub close(IO::Handle $fh)

    Closes an open file handle. It's not an error to call close on an already-closed filehandle. Returns True on success.

    It's a common idiom to use LEAVE phaser for closing the handles, which ensures the handle is closed regardless of how the block is left.

        if $do-stuff-with-the-file {
            my $fh = open "path-to-file";
            LEAVE close $fh;
            # ... do stuff with the file 
        }
     
        sub do-stuff-with-the-file (IO $path-to-file)
          my $fh = $path-to-file.open;
     
          # stick a `try` on it, since this will get run even when the sub is 
          # called with wrong arguments, in which case the `$fh` will be an `Any` 
          LEAVE try close $fh;
     
          # ... do stuff with the file 
        }
     
        given "foo/bar".IO.open(:w{
            .spurt: "I ♥ Perl 6!";
            .close;
        }

    Note: unlike some other languages, Perl 6 does not use reference counting, and so the file handles are NOT closed when they go out of scope. While they will get closed when garbage collected, garbage collection isn't guaranteed to get run. This means you must use an explicit close on handles opened for writing, to avoid data loss, and an explicit close is recommended on handles opened for reading as well, so that your program does not open too many files at the same time, triggering exceptions on further open calls.

    Note several methods allow for providing :close argument, to close the handle after the operation invoked by the method completes. As a simpler alternative, the IO::Path type provides many reading and writing methods that let you work with files without dealing with file handles directly.

    (IO::Handle) method flush

    Defined as:

    method flush(IO::Handle:D: --> True)

    Will flush the handle, writing any of the buffered data. Returns True on success; otherwise, fails with X::IO::Flush.

        given "foo".IO.open: :w {
            LEAVE .close;
            $fh.print: 'something';
            'foo'.IO.slurp.say# (if the data got buffered) OUTPUT: «␤» 
            $fh.flush;          # flush the handle 
            'foo'.IO.slurp.say# OUTPUT: «something␤» 
        }

    (IO::Handle) method native-descriptor

    Defined as:

    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.

    (IO::Handle) method nl-in

    Defined as:

    method nl-in(--> Str:Dis rw

    One of the attributes that can be set via .new or open. Defaults to ["\x0A", "\r\n"]. Takes either a Str or Array of Str specifying input line ending(s) for this handle. If .chomp attribute is set to True, will strip these endings in routines that chomp, such as get and lines.

        with 'test'.IO {
            .spurt: '1foo2bar3foo'# write some data into our test file 
            my $fh will leave {.close} = .open# can also set .nl-in via .open arg 
            $fh.nl-in = [<foo bar>]; # set two possible line endings to use; 
            $fh.lines.say# OUTPUT: ("1", "2", "3").Seq 
        }

    (IO::Handle) method nl-out

    Defined as:

    has Str:D $.nl-out is rw = "\n";

    One of the attributes that can be set via .new or open. Defaults to "\n". Takes a Str specifying output line ending for this handle, to be used by methods .put and .say.

        with 'test'.IO {
            given .open: :w {
                .put: 42;
                .nl-out = 'foo';
                .put: 42;
                .close;
            }
            .slurp.perl.say# OUTPUT: «"42\n42foo"» 
        }

    (IO::Handle) method opened

    Defined as:

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

    Returns True if the handle is open, False otherwise.

    (IO::Handle) method t

    Defined as:

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

    Returns True if the handle is opened to a TTY, False otherwise.

    Routines supplied by class Any

    IO::ArgFiles 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(--> 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 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;     # OUTPUT: «(world! hello)␤» 
    say reverse ^10;                # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)␤» 

    (Any) method sort

    Defined as:

    multi method sort()
    multi method sort(&by)

    Sorts iterables with infix:<cmp> or given code object and returns a new List. Optionally, takes a Callable as a positional parameter, specifying how to sort.

    Examples:

    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.

    <a b c d e f g>.duckmap(-> $_ where <c d e>.any { .uc }).say;
    # OUTPUT: «(a b C D E f g)␤» 
    (('d''e'), 'f').duckmap(-> $_ where <e f>.any { .uc }).say;
    # OUTPUT: «((d E) F)␤» 

    (Any) method nodemap

    Defined as:

    method nodemap(&block --> Listis nodal

    nodemap will apply &block to each element and return a new List with the return values of &block. In contrast to deepmap it will not descend recursively into sublists if it finds elements which does the Iterable role.

    say [[1,2,3], [[4,5],6,7], 7].nodemap(*+1);
    # OUTPUT: «(4, 4, 8)␤» 
     
    say [[23], [4, [56]]]».nodemap(*+1)
    # OUTPUT: «((3 4) (5 3))␤» 

    The examples above would have produced the exact same results if we had used map instead of nodemap. The difference between the two lies in the fact that map flattens out slips while nodemap doesn't.

    say [[2,3], [[4,5],6,7], 7].nodemap({.elems == 1 ?? $_ !! slip});
    # OUTPUT: «(() () 7)␤» 
    say [[2,3], [[4,5],6,7], 7].map({.elems == 1 ?? $_ !! slip});
    # OUTPUT: «(7)␤» 

    (Any) method flat

    Defined as:

    method flat(--> Seq:Dis nodal

    Interprets the invocant as a list, flattens non-containerized Iterables into a flat list, and returns that list. Keep in mind Map and Hash types are Iterable and so will be flattened into lists of pairs.

    say ((12), (3), %(:42a));      # OUTPUT: «((1 2) 3 {a => 42})␤» 
    say ((12), (3), %(:42a)).flat# OUTPUT: «(1 2 3 a => 42)␤» 

    Note that Arrays containerize their elements by default, and so flat will not flatten them. You can use hyper method call to call .List method on all the inner Iterables and so de-containerize them, so that flat can flatten them:

    say [[123], [(45), 67]]      .flat# OUTPUT: «([1 2 3] [(4 5) 6 7])␤» 
    say [[123], [(45), 67]]».List.flat# OUTPUT: «(1 2 3 4 5 6 7)␤» 

    For more fine-tuned options, see deepmap, duckmap, and signature destructuring

    (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 positional argument 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 max(&by --> Any:D)

    Coerces to Iterable and returns the numerically biggest element. If a Callable positional argument 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 positional argument 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)

    TODO

    (Any) method keys

    Defined As:

        method keys(--> TODO)

    TODO

    (Any) method flatmap

    Defined As:

        method flatmap(--> TODO)

    TODO

    (Any) method roll

    Defined As:

        method roll(--> TODO)

    TODO

    (Any) method pick

    Defined As:

        method pick(--> TODO)

    TODO

    (Any) method head

    Defined As:

        method head(--> TODO)

    TODO

    (Any) method tail

    Defined As:

        method tail(--> TODO)

    TODO

    (Any) method skip

    Defined As:

        method skip(--> TODO)

    TODO

    (Any) method prepend

    Defined As:

        method prepend(--> TODO)

    TODO

    (Any) method unshift

    Defined As:

        method unshift(--> TODO)

    TODO

    (Any) method first

    Defined As:

        method first(--> TODO)

    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)

    TODO

    (Any) method squish

    Defined As:

        method squish(--> TODO)

    TODO

    (Any) method reduce

    Defined As:

        method reduce(--> TODO)

    TODO

    (Any) method permutations

    Defined As:

        method permutations(--> TODO)

    TODO

    (Any) method categorize

    Defined As:

        method categorize(--> TODO)

    TODO

    (Any) method classify

    Defined As:

        method classify(--> TODO)

    TODO

    (Any) method produce

    Defined As:

        method produce(--> TODO)

    TODO

    (Any) method rotor

    Defined As:

        method rotor(--> TODO)

    TODO

    (Any) method pairs

    Defined As:

        method pairs(--> TODO)

    TODO

    (Any) method antipairs

    Defined As:

        method antipairs(--> TODO)

    TODO

    (Any) method kv

    Defined As:

        method kv(--> TODO)

    TODO

    (Any) method tree

    Defined As:

        method tree(--> TODO)

    TODO

    (Any) method nl-out

    Defined As:

        method nl-out(--> TODO)

    TODO

    (Any) method invert

    Defined As:

        method invert(--> TODO)

    TODO

    (Any) method combinations

    Defined As:

        method combinations(--> TODO)

    TODO

    (Any) method print-nl

    Defined As:

        method print-nl(--> TODO)

    TODO

    (Any) method iterator

    Defined As:

        method iterator(--> TODO)

    TODO

    (Any) method grep

    Defined As:

        method grep(--> TODO)

    TODO

    (Any) method match

    Defined As:

        method match(--> TODO)

    TODO

    (Any) method append

    Defined As:

        method append(--> TODO)

    TODO

    (Any) method join

    Defined As:

        method join(--> TODO)

    TODO

    (Any) method values

    Defined As:

        method values(--> TODO)

    TODO

    (Any) method collate

    Defined As:

        method collate(--> TODO)

    TODO

    (Any) method batch

    Defined As:

        method batch(--> TODO)

    TODO

    (Any) method cache

    Defined As:

        method cache(--> TODO)

    TODO

    Routines supplied by class Mu

    IO::ArgFiles 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 = 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;                # 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 Mu.new.Bool;                # 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 Capture

    Defined as:

    method Capture(Mu:D: --> Capture:D)

    Returns a Capture with named arguments corresponding to invocant's public attributes:

    class Foo {
        has $.foo = 42;
        has $.bar = 70;
        method bar { 'something else' }
    }.new.Capture.say# OUTPUT: «\(:bar("something else"), :foo(42))␤» 

    (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(+args --> 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, for non-Str types, so say $something and say $something.gist generally produce the same output.

    say Mu.gist;        # OUTPUT: «(Mu)␤» 
    say Mu.new.gist;    # OUTPUT: «Mu.new␤» 

    (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:{
            "Point($.x$.y)";
        }
    }
     
    my $p = Point2D.new(x => 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{
            self.bless(:$x:$y);
        }
    }
    my $p = Point.new(-11);

    (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) 
    {
    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 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 $verbose-selected.so {
        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␤»