class Proc::Async

Running process (asynchronous interface)

class Proc::Async {}

Note: only the MoarVM backend of Rakudo implements Proc::Async at the moment.

Proc::Async allows you to run external commands asynchronously, capturing standard output and error handles, and optionally write to its standard input.

my $file = foo.IO;
spurt $fileand\nCamelia\n\nme\n;
 
my $proc = Proc::Async.new: :wtac--$file-;
# my $proc = Proc::Async.new: :w, ‘sleep’, 15; # uncomment to try timeouts 
 
react {
    whenever $proc.stdout.lines { # split input on \r\n, \n, and \r 
        say line: $_
    }
    whenever $proc.stderr { # chunks 
        say stderr: $_
    }
    whenever $proc.start {
        say Proc finished. Exit code: .exitcode;
        done # gracefully jump from the react block 
    }
    whenever $proc.print: I\n\nCamelia\n {
        $proc.close-stdin
    }
    whenever signal(SIGTERM).merge: signal(SIGINT{
        once {
            say Signal received, asking the process to stop;
            $proc.kill# sends SIGHUP, change appropriately 
            whenever signal($_).zip: Promise.in(2).Supply {
                say Kill it!;
                $proc.kill: SIGKILL
            }
        }
    }
    whenever Promise.in(10{
        say Timeout. Asking the process to stop;
        $proc.kill# sends SIGHUP, change appropriately 
        whenever Promise.in(2{
            say Timeout. Forcing the process to stop;
            $proc.kill: SIGKILL
        }
    }
}
 
say Program finished;

Example above produces the following output:

line: me
line: ♡
line: Camelia
line: and
line: Camelia
line: ♥
line: I
Proc finished. Exit code: 0
Program finished

Note: Using .zip and .merge as suggested above is known not to work in Rakudo releases before 2017.09.

Alternatively, you can use Proc::Async without using a react block:

# command with arguments 
my $proc = Proc::Async.new('echo''foo''bar');
 
# subscribe to new output from out and err handles: 
$proc.stdout.tap(-> $v { print "Output: $v" }quit => { say 'caught exception ' ~ .^name });
$proc.stderr.tap(-> $v { print "Error:  $v" });
 
say "Starting...";
my $promise = $proc.start;
 
# wait for the external program to terminate 
await $promise;
say "Done.";

This produces the following output:

Starting...
Output: foo bar
Done.

An example that opens an external program for writing:

use v6;
my $prog = Proc::Async.new(:w'hexdump''-C');
my $promise = $prog.start;
await $prog.write(Buf.new(1242));
$prog.close-stdin;
await $promise;

An example of piping several commands like echo "Hello, world" | cat -n:

use v6;
my $proc-echo = Proc::Async.new: 'echo''Hello, world';
my $proc-cat = Proc::Async.new: 'cat''-n';
$proc-cat.bind-stdin: $proc-echo.stdout;
await $proc-echo.start$proc-cat.start;

Methods

method new

multi method new(*@ ($path*@args), :$w:$enc:$translate-nl --> Proc::Async:D)
multi method new(   :$path:@args,  :$w:$enc:$translate-nl --> Proc::Async:D)

Creates a new Proc::Async object with external program name or path $path and the command line arguments @args.

If :w is passed to new, then a pipe to the external program's standard input stream (stdin) is opened, to which you can write with write and say.

The :enc specifies the encoding for streams (can still be overridden in individual methods) and defaults to utf8.

If :translate-nl is set to True (default value), OS-specific newline terminators (e.g. \r\n on Windows) will be automatically translated to \n.

method stdout

method stdout(Proc::Async:D: :$bin --> Supply:D)

Returns the Supply for the external program's standard output stream. If :bin is passed, the standard output is passed along in binary as Blob, otherwise it is interpreted as UTF-8, decoded, and passed along as Str.

my $proc = Proc::Async.new(:r'echo''Perl 6');
$proc.stdout.tap-> $str {
    say "Got output '$str' from the external program";
});
my $promise = $proc.start;
await $promise;

You must call stdout before you call method start. Otherwise an exception of class X::Proc::Async::TapBeforeSpawn is thrown.

If stdout is not called, the external program's standard output is not captured at all.

Note that you cannot call stdout both with and without :bin on the same object; it will throw an exception of type X::Proc::Async::CharsOrBytes if you try.

Use .Supply for merged STDOUT and STDERR.

method stderr

method stderr(Proc::Async:D: :$bin --> Supply:D)

Returns the Supply for the external program's standard error stream. If :bin is passed, the standard error is passed along in binary as Blob, otherwise it is interpreted as UTF-8, decoded, and passed along as Str.

my $proc = Proc::Async.new(:r'echo''Perl 6');
$proc.stderr.tap-> $str {
    say "Got error '$str' from the external program";
});
my $promise = $proc.start;
await $promise;

You must call stderr before you call method start. Otherwise an exception of class X::Proc::Async::TapBeforeSpawn is thrown.

If stderr is not called, the external program's standard error stream is not captured at all.

Note that you cannot call stderr both with and without :bin on the same object; it will throw an exception of type X::Proc::Async::CharsOrBytes if you try.

Use .Supply for merged STDOUT and STDERR.

method bind-stdin

multi method bind-stdin(IO::Handle:D $handle)
multi method bind-stdin(Proc::Async::Pipe:D $pipe)

Sets a handle or a Pipe as a source of STDIN. STDIN of the target process must be writable or X::Proc::Async::BindOrUse will be thrown.

method bind-stdout

method bind-stdout(IO::Handle:D $handle)

Redirects STDOUT of the target process to a handle. If STDOUT is closed X::Proc::Async::BindOrUse will be thrown.

Sets a w

method bind-stderr

method bind-stderr(IO::Handle:D $handle)

Redirects STDERR of the target process to a handle. If STDERR is closed X::Proc::Async::BindOrUse will be thrown.

method w

method w(Proc::Async:D:)

Returns a true value if :w was passed to the constructor, that is, if the external program is started with its input stream made available to output to the program through the .print, .say and .write methods.

method start

method start(Proc::Async:D: :$scheduler = $*SCHEDULER:$cwd = $*CWD --> Promise:D)

Initiates spawning of the external program. Returns a Promise that will be kept with a Proc object once the external program exits, and that will be broken if the program cannot be started.

If start is called on a Proc::Async object on which it has already been called before, an exception of type X::Proc::Async::AlreadyStarted is thrown.

Note: If you wish to await the Promise and discard its result, using

try await $p.start;

will throw if the program exited with non-zero status, as the Proc returned as the result of the Promise throws when sunk and in this case it will get sunk outside the try. To avoid that, sink it yourself inside the try:

try sink await $p.start;

method started

method started(Proc::Async:D: --> Bool:D)

Returns False before .start has been called, and True afterwards.

method ready

method ready(Proc::Async:D: --> Promise:D)

Returns a Promise that will be kept once the process has successfully started. Promise will be broken if the program fails to start.

method path

method path(Proc::Async:D:)

Returns the name and/or path of the external program that was passed to the new method as first argument.

method args

method args(Proc::Async:D: --> Positional:D)

Returns the command line arguments for the external programs, as passed to the new method.

method write

method write(Proc::Async:D: Blob:D $b:$scheduler = $*SCHEDULER --> Promise:D)

Write the binary data in $b to the standard input stream of the external program.

Returns a Promise that will be kept once the data has fully landed in the input buffer of the external program.

The Proc::Async object must be created for writing (with Proc::Async.new(:w, $path, @args)). Otherwise an X::Proc::Async::OpenForWriting exception will the thrown.

start must have been called before calling method write, otherwise an X::Proc::Async::MustBeStarted exception is thrown.

method print

method print(Proc::Async:D: Str(Any$str:$scheduler = $*SCHEDULER)

Write the text data in $str to the standard input stream of the external program, encoding it as UTF-8.

Returns a Promise that will be kept once the data has fully landed in the input buffer of the external program.

The Proc::Async object must be created for writing (with Proc::Async.new(:w, $path, @args)). Otherwise an X::Proc::Async::OpenForWriting exception will the thrown.

start must have been called before calling method print, otherwise an X::Proc::Async::MustBeStarted exception is thrown.

method say

method say(Proc::Async:D: $output:$scheduler = $*SCHEDULER)

Calls method gist on the $output, adds a newline, encodes it as UTF-8, and sends it to the standard input stream of the external program, encoding it as UTF-8.

Returns a Promise that will be kept once the data has fully landed in the input buffer of the external program.

The Proc::Async object must be created for writing (with Proc::Async.new(:w, $path, @args)). Otherwise an X::Proc::Async::OpenForWriting exception will the thrown.

start must have been called before calling method say, otherwise an X::Proc::Async::MustBeStarted exception is thrown.

method Supply

multi method Supply(Proc::Async:D: :$bin!)
multi method Supply(Proc::Async:D: :$enc:$translate-nl)

Returns a Supply of merged stdout and stderr streams. If :$bin named argument is provided, the Supply will be binary, producing Buf objects, otherwise, it will be in character mode, producing Str objects and :$enc named argument can specify encoding to use. The :$translate-nl option specifies whether new line endings should be translated for to match those used by the current operating system (e.g. \r\n on Windows).

react {
    with Proc::Async.new: «"$*EXECUTABLE" -e 'say 42; note 100'» {
        whenever .Supply { .print }  # OUTPUT: «42␤100␤» 
        whenever .start {}
    }
}

It is an error to create both binary and non-binary .Supply. It is also an error to use both .Supply and either stderr or stdout supplies.

method close-stdin

method close-stdin(Proc::Async:D:)

Closes the standard input stream of the external program. Programs that read from STDIN often only terminate when their input stream is closed. So if waiting for the promise from method start hangs (for a program opened for writing), it might be a forgotten close-stdin.

The Proc::Async object must be created for writing (with Proc::Async.new(:w, $path, @args)). Otherwise an X::Proc::Async::OpenForWriting exception will the thrown.

start must have been called before calling method close-stdin, otherwise an X::Proc::Async::MustBeStarted exception is thrown.

method kill

method kill(Proc::Async:D: $signal = "HUP")

Sends a signal to the running program. The signal can be a signal name ("KILL" or "SIGKILL"), an integer (9) or an element of the Signal enum (Signal::SIGKILL).

Type Graph

Type relations for Proc::Async
perl6-type-graph Proc::Async Proc::Async Any Any Proc::Async->Any Mu Mu Any->Mu

Stand-alone image: vector

Routines supplied by class Any

Proc::Async 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:

multi method list(Any:U: -->List)
multi method list(Any:D \SELF: -->List)

Applies the infix , operator to the invocant and returns the resulting 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;
say %h<a>;     # OUTPUT: «(Any)␤»      <-- Undefined 
%h<a>.push(1); # .push on Any 
say %h;        # OUTPUT: «{a => [1]}␤» <-- 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(&custom-routine-to-use)

Sorts iterables with cmp or given code object and returns a new Seq. 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)

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.

say [[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.

my  $range = 1..5;
say $range;         # OUTPUT: «1..5␤» 
say $range.eager;   # OUTPUT: «(1 2 3 4 5)␤» 

(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 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 or zero if no value has been specified. The exit value ($status), when different from zero, has to be opportunely evaluated from the process that catches it (e.g., a shell).

exit does prevent the LEAVE phaser to be executed.

exit should be used as last resort only to signal the parent process about an exit code different from zero, and should not be used to terminate exceptionally a method or a sub: use exceptions instead.

It is worth noting that the only way to return an exit code different from zero from a Main function is by means of using exit.

(Any) sub item

Defined as:

proto sub item(|) is pure
multi item(\x)
multi item(|c)
multi 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, using the list method.

(Any) method Hash

Defined as:

proto method Hash(|) is nodal
multi method Hash--> Hash:D)

Coerce the invocant to Hash by invoking the method hash on it.

(Any) method hash

Defined as:

proto method hash(|) is nodal
multi method hash(Any:U: --> Hash:D)
multi method hash(Any:D: --> Hash:D)

Creates a new Hash, empty in the case the invocant is undefined, or coerces the invocant to an Hash in the case it is defined.

my $d# $d is Any 
say $d.hash# OUTPUT: {} 
$d.append: 'a''b';
say $d.hash# OUTPUT: {a => b} 

(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 by applying the invocant's .list method, and then to a Supply.

(Any) method min

Defined As:

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

Coerces to Iterable and returns the numerically smallest element.

If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original value is still the one returned from min.

say (1,7,3).min();       # OUTPUT:«1␤» 
say (1,7,3).min({1/$_}); # OUTPUT:«7␤» 

(Any) method max

Defined As:

multi method max(--> Any:D)
multi method max(&filter --> Any:D)

Coerces to Iterable and returns the numerically largest element.

If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original value is still the one returned from max.

say (1,7,3).max();       # OUTPUT:«7␤» 
say (1,7,3).max({1/$_}); # OUTPUT:«1␤» 

(Any) method minmax

Defined As:

multi method minmax(--> Range:D)
multi method minmax(&filter --> Range:D)

Returns a Range from the smallest to the largest element.

If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original values are still used in the returned Range.

say (1,7,3).minmax();      # OUTPUT:«1..7␤» 
say (1,7,3).minmax({-$_}); # OUTPUT:«7..1␤» 

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

Defined As:

multi method keys(Any:U: --> List)
multi method keys(Any:D: --> List)

For defined Any returns its keys after calling list on it, otherwise calls list and returns it.

say Any.keys# OUTPUT: «()␤» 

(Any) method flatmap

Defined As:

method flatmap(Any:U: &code --> Seq)

Coerces the Any to a list by applying the .list method and uses List.flatmap on it.

say Any.flatmap({.reverse}); # OUTPUT: «((Any))␤» 

In the case of Any, Any.list returns a 1-item list, as is shown.

(Any) method roll

Defined As:

multi method roll(--> Any)
multi method roll($n --> Seq)

Coerces the invocant Any to a list by applying the .list method and uses List.roll on it.

say Any.roll;    # OUTPUT: «(Any)␤» 
say Any.roll(5); # OUTPUT: «((Any) (Any) (Any) (Any) (Any))␤» 

(Any) method pick

Defined As:

multi method pick(--> Any)
multi method pick($n --> Seq)

Coerces the Any to a list by applying the .list method and uses List.pick on it.

say Any.pick;    # OUTPUT: «(Any)␤» 
say Any.pick(5); # OUTPUT: «((Any))␤» 

(Any) method skip

Defined As:

multi method skip(--> Seq)
multi method skip($n --> Seq)

Creates a Seq from 1-item list's iterator and uses Seq.skip on it.

say Any.skip;      # OUTPUT: «()␤» 
say Any.skip(5);   # OUTPUT: «()␤» 
say Any.skip(-1);  # OUTPUT: «((Any))␤» 
say Any.skip(*-1); # OUTPUT: «((Any))␤» 

(Any) method prepend

Defined As:

multi method prepend(--> Array)
multi method prepend(@values --> Array)

Initializes Any variable as empty Array and calls Array.prepend on it.

my $a;
say $a.prepend# OUTPUT: «[]␤» 
say $a;         # OUTPUT: «[]␤» 
my $b;
say $b.prepend(1,2,3); # OUTPUT: «[1 2 3]␤» 

(Any) method unshift

Defined As:

multi method unshift(--> Array)
multi method unshift(@values --> Array)

Initializes Any variable as empty Array and calls Array.unshift on it.

my $a;
say $a.unshift# OUTPUT: «[]␤» 
say $a;         # OUTPUT: «[]␤» 
my $b;
say $b.unshift([1,2,3]); # OUTPUT: «[[1 2 3]]␤» 

(Any) method first

Defined As:

method first(Mu $matcher?:$k:$kv:$p:$end)

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

say Any.first# OUTPUT: «(Any)␤» 

(Any) method unique

Defined As:

method unique(:&as:&with --> Seq:D)

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

say Any.unique# OUTPUT: «((Any))␤» 

(Any) method repeated

Defined As:

method repeated(:&as:&with --> Seq)

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

say Any.repeated# OUTPUT: «()␤» 

(Any) method squish

Defined As:

method squish(:&as:&with --> Seq)

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

say Any.squish# OUTPUT: «((Any))␤» 

(Any) method permutations

Defined As:

method permutations(--> Seq)

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

say Any.permutations# OUTPUT: «(((Any)))␤» 

(Any) method categorize

Defined As:

method categorize(&mapper --> Hash:D)

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

say Any.categorize({ $_ }); # OUTPUT: «{(Any) => [(Any)]}␤» 

(Any) method classify

Defined As:

method classify(&mapper -->Hash:D)

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

say Any.classify({ $_ }); # OUTPUT: «{(Any) => [(Any)]}␤» 

(Any) method produce

(Any) method pairs

Defined As:

multi method pairs(Any:U:  -->List)
multi method pairs(Any:D:  -->List)

Returns an empty List if the invocant is undefined, otherwise converts the invocant to a List via the list method and calls List.pairs on it:

say Any.pairs# OUTPUT: «()␤» 
my $a;
say $a.pairs;  # OUTPUT: «()» 
$a = Any.new;
say $a.pairs;  # OUTPUT: «(0 => Any.new)» 

(Any) method antipairs

Defined As:

multi method antipairs(Any:U:  -->List)
multi method antipairs(Any:D:  -->List)

Applies the method List.antipairs to the invocant, if it is defined, after having invoked list on it. If the invocant is not defined, it returns an empty List:

my $a;
say $a.antipairs;      # OUTPUT: «()» 
$a = Any.new;
say $a.antipairs;      # OUTPUT: «(Any.new => 0)» 

(Any) method kv

Defined As:

multi method kv(Any:U:  -->List)
multi method kv(Any:D:  -->List)

Returns an empty List if the invocant is not defined, otherwise it does invoke list on the invocant and then returns the result of List.kv on the latter:

my $a;
say $a.kv;      # OUTPUT: «()» 
$a = Any.new;
say $a.kv;      # OUTPUT: «(0 Any.new)» 
say Any.kv;     # OUTPUT: «()␤» 

(Any) method toggle

Defined as:

method toggle(Any:D: *@conditions where .all ~~ Callable:DBool :$off  --> Seq:D)

Iterates over the invocant, producing a Seq, toggling whether the received values are propagated to the result on and off, depending on the results of calling Callables in @conditions:

say ^10 .toggle: * < 4* %% 2&is-prime# OUTPUT: «(0 1 2 3 6 7)␤» 
say ^10 .toggle: :off* > 4;              # OUTPUT: «(5 6 7 8 9)␤» 

Imagine a switch that's either on or off (True or False), and values are produced if it's on. By default, the initial state of that switch is in "on" position, unless :$off is set to a true value, in which case the initial state will be "off".

A Callable from the head of @conditions is taken (if any are available) and it becomes the current tester. Each value from the original sequence is tested by calling the tester Callable with that value. The state of our imaginary switch is set to the return value from the tester: if it's truthy, set switch to "on", otherwise set it to "off".

Whenever the switch is toggled (i.e. switched from "off" to "on" or from "on" to "off"), the current tester Callable is replaced by the next Callable in @conditions, if available, which will be used to test any further values. If no more tester Callables are available, the switch will remain in its current state until the end of iteration.

# our original sequence of elements: 
say list ^10# OUTPUT: «(0 1 2 3 4 5 6 7 8 9)␤» 
# toggled result: 
say ^10 .toggle: * < 4* %% 2&is-prime# OUTPUT: «(0 1 2 3 6 7)␤» 
 
# First tester Callable is `* < 4` and initial state of switch is "on". 
# As we iterate over our original sequence: 
# 0 => 0 < 4 === True  switch is on, value gets into result, switch is 
#                      toggled, so we keep using the same Callable: 
# 1 => 1 < 4 === True  same 
# 2 => 2 < 4 === True  same 
# 3 => 3 < 4 === True  same 
# 4 => 4 < 4 === False switch is now off, "4" does not make it into the 
#                      result. In addition, our switch got toggled, so 
#                      we're switching to the next tester Callable 
# 5 => 5 %% 2 === False  switch is still off, keep trying to find a value 
# 6 => 6 %% 2 === True   switch is now on, take "6" into result. The switch 
#                        toggled, so we'll use the next tester Callable 
# 7 => is-prime(7) === True  switch is still on, take value and keep going 
# 8 => is-prime(8) === False switch is now off, "8" does not make it into 
#                            the result. The switch got toggled, but we 
#                            don't have any more tester Callables, so it 
#                            will remain off for the rest of the sequence. 

Since the toggle of the switch's state loads the next tester Callable, setting :$off to a True value affects when first tester is discarded:

# our original sequence of elements: 
say <0 1 2># OUTPUT: «(0 1 2)␤» 
# toggled result: 
say <0 1 2>.toggle: * > 1# OUTPUT: «()␤» 
 
# First tester Callable is `* > 1` and initial state of switch is "on". 
# As we iterate over our original sequence: 
# 0 => 0 > 1 === False  switch is off, "0" does not make it into result. 
#                      In addition, switch got toggled, so we change the 
#                      tester Callable, and since we don't have any more 
#                      of them, the switch will remain "off" until the end 
# our original sequence of elements: 
say <0 1 2># OUTPUT: «(0 1 2)␤» 
# toggled result: 
say <0 1 2>.toggle: :off* > 1# OUTPUT: «(2)␤» 
 
# First tester Callable is `* > 1` and initial state of switch is "off". 
# As we iterate over our original sequence: 
# 0 => 0 > 1 === False  switch is off, "0" does not make it into result. 
#                       The switch did NOT get toggled this time, so we 
#                       keep using our current tester Callable 
# 1 => 1 > 1 === False  same 
# 2 => 2 > 1 === True   switch is on, "2" makes it into the result 

(Any) method tree

Defined As:

method tree(--> Any)

Returns the class if it's undefined or if it's not iterable, returns the result of applying the tree method to the elements if it's Iterable.

say Any.tree# OUTPUT: «Any␤» 

.tree has different prototypes for Iterable elements.

my @floors = ( 'A', ('B','C', ('E','F','G')));
say @floors.tree(1).flat.elems# OUTPUT: «6␤» 
say @floors.tree(2).flat.elems# OUTPUT: «2␤» 
say @floors.tree*.join("-"), *.join(""), *.join("|" )); # OUTPUT: «A-B—C—E|F|G␤» 

With a number, it iteratively applies tree to every element in the lower level; the first instance will apply .tree(0) to every element in the array, and likewise for the next example.

The second prototype applies the Whatever code passed as arguments to every level in turn; the first argument will go to level 1 and so on. tree can, thus, be a great way to process complex all levels of complex, multi-level, data structures.

(Any) method nl-out

Defined As:

method nl-out(--> Str)

Returns Str with the value of "\n". See IO::Handle.nl-out for the details.

say Any.nl-out# OUTPUT: «␤␤» 

(Any) method invert

Defined As:

method invert(--> List)

Returns an empty List.

say Any.invert# OUTPUT: «()␤» 

(Any) method combinations

Defined As:

method combinations(--> Seq)

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

say Any.combinations# OUTPUT: «(() ((Any)))␤» 

(Any) method iterator

Defined As:

method iterator(--> Iterator)

Coerces the Any to a list by applying the .list method and uses iterator on it.

my $it = Any.iterator;
say $it.pull-one# OUTPUT: «(Any)␤» 
say $it.pull-one# OUTPUT: «IterationEnd␤» 

(Any) method grep

Defined As:

method grep(Mu $matcher:$k:$kv:$p:$v --> Seq)

Coerces the Any to a list by applying the .list method and uses List.grep on it.

Based on $matcher value can be either ((Any)) or empty List.

my $a;
say $a.grep({ True }); # OUTPUT: «((Any))␤» 
say $a.grep({ $_ });   # OUTPUT: «()␤» 

(Any) method append

Defined As:

proto method append(|) is nodal {*}
multi method append(Any:U \SELF: |values --> Array)

In the case the instance is not a positional-thing, it instantiate it as a new Array, otherwise clone the current instance. After that, it appends the values passed as arguments to the array obtained calling Array.append on it.

my $a;
say $a.append# OUTPUT: «[]␤» 
my $b;
say $b.append((1,2,3)); # OUTPUT: «[1 2 3]␤» 

(Any) method values

Defined As:

method values(--> List)

Returns an empty List.

(Any) method collate

Defined As:

method collate(--> Seq)

TODO

(Any) method cache

Defined As:

method cache(--> List)

Provides a List representation of the object itself, calling the method list on the instance.

Routines supplied by class Mu

Proc::Async inherits from class Mu, which provides the following methods:

(Mu) method defined

Declared as

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 defined

Declared as

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

invokes the .defined method on the object and returns its result.

(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

Declared 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, 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 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, including shallow cloning of private attributes. 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)␤» 

Note that .clone does not go the extra mile to shallow-copy @. and %. sigiled attributes and, if modified, the modifications will still be available in the original object:

class Foo {
    has $.foo is rw = 42;
    has &.boo is rw = { say "Hi" };
    has @.bar       = <a b>;
    has %.baz       = <a b c d>;
}
 
my $o1 = Foo.new;
with my $o2 = $o1.clone {
    .foo = 70;
    .bar = <Z Y>;
    .baz = <Z Y X W>;
    .boo = { say "Bye" };
}
 
# Hash and Array attribute modifications in clone appear in original as well: 
say $o1;    # OUTPUT: «Foo.new(foo => 42, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …␤» 
say $o2;    # OUTPUT: «Foo.new(foo => 70, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …␤» 
$o1.boo.(); # OUTPUT: «Hi␤» 
$o2.boo.(); # OUTPUT: «Bye␤» 

To clone those, you could implement your own .clone that clones the appropriate attributes and passes the new values to Mu.clone, for example, via nextwith. Alternatively, your own .clone could clone self first (using self.Mu::clone or callsame) and then manipulate the clone as needed, before returning it.

class Bar {
    has @.foo = <a b>;
    has %.bar = <a b c d>;
    method clone { nextwith :foo(@!foo.clone:bar(%!bar.clone}
}
 
my $o1 = Bar.new;
with my $o2 = $o1.clone {
    .foo = <Z Y>;
    .bar = <Z Y X W>;
}
 
# Hash and Array attribute modifications in clone do not affect original: 
say $o1# OUTPUT: «Bar.new(foo => ["a", "b"], bar => {:a("b"), :c("d")})␤» 
say $o2# OUTPUT: «Bar.new(foo => ["Z", "Y"], bar => {:X("W"), :Z("Y")})␤» 

(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(--> Pod::Block::Declarator)

Returns the attached Pod::Block::Declarator.

For instance:

#| Initiate a specified spell normally 
sub cast(Spell $s{
  do-raw-magic($s);
}
#= (do not use for class 7 spells) 
say &cast.WHY;
# OUTPUT: «Initiate a specified spell normally␤(do not use for class 7 spells)␤» 

See Pod declarator blocks 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 };
say 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␤»