## dist_cpan-GARLANDG-IO-URing.md
# NAME

IO::URing - Access the io\_uring interface from Raku

# SYNOPSIS

Sample NOP call

```
use IO::URing;

my IO::URing $ring .= new(:8entries, :0flags);
my $data = await $ring.nop(1);
# or
react whenever $ring.nop(1) -> $data {
    say "data: {$data.raku}";
  }
}
$ring.close; # free the ring

```

# DESCRIPTION

IO::URing is a binding to the new io\_uring interface in the Linux kernel.

It will only work on Linux 5.6 and above. Use 5.10 or higher for best results. See the io\_uring documentation for which operations are supported on your kernel version.

See the included IO::URing::Socket libraries for an example of IO::URing in action.

Some knowledge of io\_uring and liburing is a pre-requisite for using this library. This code uses liburing to set up and submit requests to the ring.

# IO::URing internal classes

## class IO::URing::Completion

A Completion is returned from an awaited Handle. The completion contains the result of the operation.

### has Mu $.data

The user data passed into the submission.

### has io\_uring\_sqe $.request

The request passed into the IO::URing.

### has int $.result

The result of the operation.

## class IO::URing::Handle

A Handle is a Promise that can be used to cancel an IO::URing operation. Every call to submit or any non-prep operation will return a Handle.

# IO::URing

## IO::URing methods

### method close

```
method close() returns Mu

```

Close the IO::URing object and shut down event processing.

### method features

```
method features() returns Mu

```

Get the enabled features on this IO::URing.

### method prep-nop

```
method prep-nop(
    Int :$ioprio = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a no-op operation.

### method nop

```
method nop(
    |c
) returns IO::URing::Handle

```

Prepare and submit a no-op operation.

### multi method prep-readv

```
multi method prep-readv(
    Int $fd,
    @bufs,
    Int :$offset = 0,
    :$data,
    Int :$ioprio = 0,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a readv operation. A multi will handle a non-Int $fd by calling native-descriptor. A multi with a @bufs slurpy is provided.

### method readv

```
method readv(
    |c
) returns IO::URing::Handle

```

Prepare and submit a readv operation. See prep-readv for details.

### multi method prep-writev

```
multi method prep-writev(
    Int $fd,
    @bufs,
    Int :$offset = 0,
    Int :$ioprio = 0,
    :$data,
    :$enc = "utf-8",
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a writev operation. A multi will handle a non-Int $fd by calling native-descriptor. A multi with a @bufs slurpy is provided.

### method writev

```
method writev(
    |c
) returns IO::URing::Handle

```

Prepare and submit a writev operation. See prep-writev for details.

### multi method prep-fsync

```
multi method prep-fsync(
    Int $fd,
    Int $fsync-flags where { ... } = 0,
    Int :$ioprio = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare an fsync operation. fsync-flags can be set to IORING\_FSYNC\_DATASYNC to use fdatasync(2) instead. Defaults to fsync(2).

### method fsync

```
method fsync(
    $fd,
    Int $fsync-flags where { ... } = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit an fsync operation. See prep-fsync for details.

### multi method prep-poll-add

```
multi method prep-poll-add(
    Int $fd,
    Int $poll-mask where { ... },
    Int :$ioprio = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a poll-add operation. A multi will handle a non-Int $fd by calling native-descriptor.

### method poll-add

```
method poll-add(
    $fd,
    Int $poll-mask where { ... },
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a poll-add operation. See prep-poll-add for details.

### method prep-poll-remove

```
method prep-poll-remove(
    IO::URing::Handle $slot,
    Int :$ioprio = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a poll-remove operation. The provided Handle must be the Handle returned by the poll-add operation that should be cancelled.

### method poll-remove

```
method poll-remove(
    IO::URing::Handle $slot,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a poll-remove operation.

### multi method prep-sendto

```
multi method prep-sendto(
    Int $fd,
    Str $str,
    Int $union-flags,
    sockaddr_role $addr,
    Int $len,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async,
    :$enc = "utf-8"
) returns IO::URing::Handle

```

Prepare a sendmsg operation, mimicking sendto(2). A multi is provided that takes Blobs. A multi will handle a non-Int $fd by calling native-descriptor.

### multi method sendto

```
multi method sendto(
    Int $fd,
    Blob $blob,
    Int $union-flags,
    sockaddr_role $addr,
    Int $len,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a sendmsg operation, mimicking sendto(2).

### multi method prep-sendmsg

```
multi method prep-sendmsg(
    Int $fd,
    msghdr:D $msg,
    $union-flags,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a sendmsg operation. A multi will handle a non-Int $fd by calling native-descriptor.

### method sendmsg

```
method sendmsg(
    $fd,
    msghdr:D $msg,
    $flags,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a sendmsg operation.

### multi method prep-recvfrom

```
multi method prep-recvfrom(
    Int $fd,
    Blob $buf,
    $flags,
    Blob $addr,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a recvmsg operation, mimicking recvfrom(2). A multi is provided that takes Blobs. A multi will handle a non-Int $fd by calling native-descriptor.

### method recvfrom

```
method recvfrom(
    $fd,
    Blob $buf,
    $flags,
    Blob $addr,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a recvmsg operation, mimicking recvfrom(2).

### multi method prep-recvmsg

```
multi method prep-recvmsg(
    Int $fd,
    msghdr:D $msg is rw,
    $union-flags,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a recvmsg operation. A multi will handle a non-Int $fd by calling native-descriptor.

### multi method recvmsg

```
multi method recvmsg(
    Int $fd,
    msghdr:D $msg is rw,
    $flags,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a recvmsg operation

### method prep-cancel

```
method prep-cancel(
    IO::URing::Handle $slot,
    Int $union-flags where { ... } = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a cancel operation to cancel a previously submitted operation. Note that this chases an in-flight operation, meaning it may or maybe not be successful in cancelling the operation. This means that both cases must be handled.

### method cancel

```
method cancel(
    IO::URing::Handle $slot,
    Int :$flags where { ... } = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a cancel operation

### multi method prep-accept

```
multi method prep-accept(
    Int $fd,
    $sockaddr = Str,
    Int $union-flags = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare an accept operation. A multi will handle a non-Int $fd by calling native-descriptor.

### method accept

```
method accept(
    $fd,
    $sockaddr?,
    Int $union-flags = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit an accept operation.

### multi method prep-connect

```
multi method prep-connect(
    Int $fd,
    sockaddr_role $sockaddr,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a connect operation. A multi will handle a non-Int $fd by calling native-descriptor.

### method connect

```
method connect(
    $fd,
    sockaddr_role $sockaddr,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a connect operation.

### multi method prep-send

```
multi method prep-send(
    Int $fd,
    Blob $buf,
    $union-flags = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a send operation. A multi will handle a Str submission., which takes a named parameter :$enc = 'utf-8'. A multi will handle a non-Int $fd by calling native-descriptor.

### multi method send

```
multi method send(
    $fd,
    $buf,
    Int $flags = 0,
    :$enc = "utf-8",
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a send operation.

### multi method prep-recv

```
multi method prep-recv(
    Int $fd,
    Blob $buf,
    Int $union-flags = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a recv operation. A multi will handle a non-Int $fd by calling native-descriptor.

### multi method recv

```
multi method recv(
    $fd,
    Blob $buf,
    Int $union-flags = 0,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a recv operation.

### multi method prep-close-fd

```
multi method prep-close-fd(
    Int $fd,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare a close operation. A multi will handle a non-Int $fd by calling native-descriptor.

### method close-fd

```
method close-fd(
    Int $fd,
    :$data,
    :$drain,
    :$link,
    :$hard-link,
    :$force-async
) returns IO::URing::Handle

```

Prepare and submit a close operation.

### multi method supported-ops

```
multi method supported-ops() returns Hash

```

Get the supported operations on an IO::URing instance.

### multi method supported-ops

```
multi method supported-ops() returns Hash

```

Get the supported operations without an IO::URing instance.

# AUTHOR

Travis Gibson [TGib.Travis@protonmail.com](mailto:TGib.Travis@protonmail.com)

# COPYRIGHT AND LICENSE

Copyright 2021 Travis Gibson

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.

Some of the subs in this library were translated from liburing into Raku. Liburing is licensed under a dual LGPL and MIT license. Thank you Axboe for this library and interface.


## dist_cpan-HANENKAMP-Future.md
# NAME

Future - A futuristic extension to Promises and other awaitables

# SYNOPSIS

```
use Future;

# Works like Promise.start({})
my $f = Future.start: { long-running-process() };
my $result = await $f;

# Or from a Promise.new
my $p = Promise.new;
my $f = Future.from-promise($p);
$p.keep(42);
my $result = await $f;

# But you can add types
my Future[Int] $f .= start: { long-running-process() };
my $result = await $f; # guaranteed to be an Int or throws exception
CATCH { when X::Future::Mismatch { .say } }

# And nested Futures automatically unravel nested Futures/Promises
my $f = Future.start: {
    start { 42 }
}
say await $f; # prints 42, not Promise.new(...)

# Callback chains have entirely different semantics from Promise
# - catch() - allows you to handle exceptions
# - then() - allows for asynchronous processing
my Future[Int] $i = Future.start(
    { open('file.txt', :r) }
).catch(
    -> X::IO { open('alt.txt', :r) }
).catch(
    -> X::IO { "42" }
).then(
    -> Str $val { $val.Numeric },
    -> IO::Handle $fh { $fh.slurp.Numeric },
).constrain(Int);

say await $i;

```

# DESCRIPTION

**EXPERIMENTAL.** This is an experimental API. Suggestions welcome.

Promises are wonderful, but having become accustomed to some of the features of promises in other languages, I found a few things lacking. I wanted to make something that made Promises a little nicer to work with. So to the <Future>.

A <Future> is just a placeholder for a future value. It does not directly provide any means of resolving that value. Instead, it depends on something else to eventually provide that value:

* The `.start()` method takes a block which will run on a new thread. The return value from the block becomes the future value.
* The `.awaitable()` method takes any object that can be used with `await`. The Future will get the value of that object whenever `await` returns it.
* The `.immediate()` takes a value which immediately fulfills the Future.
* The `.exceptional()` takes an <Exception>, which creates a rejected Future.

This means a Future can get its value from basically anything, including a <Promise>, <Supply>, or <Channel>.

A <Future> provides asynchronous callbacks similar to those of <Promise>. These will be called when the future is fulfilled or rejected. This is different from a <Promise>, whose callbacks are only called when the Promise is kept. The callbacks are executed using a form of multi-dispatch, so multiple alternative callbacks can be provided and the callback chosen is based upon its signature.

The action of the callbacks is based on the method used to register them:

* `.then()` These callbacks are executed on fulfillment.
* `.catch()` These callbacks are executed on rejection.

Each of these return a new <Future> that will be fulfilled after the original Future is fulfilled and the callback completes. The actual semantics of how each these calls work is subtly different, but are loosely based upon the differences in how Perl 6 handles multi-subs, CATCH-blocks, and LAST-blocks.

A <Future> is also type-aware. I often want to return a <Promise> from a method, but then I have to explicitly document what that Promise is actually supposed to return. This is no longer a problem with Future:

```
# This is bleh
method fib($n --> Promise) { ... }

# This is nice
method fib($n --> Future[Int]) { ... }

```

You can create a <Future> with an explicitly parameterized type or you can use the `.constrain()` method to take an existing Future and apply that type expectation. The latter should be done at the end of a callback chain because it's only the final fulfillment that ought to be constrained to the final result type. (Though, you may, of course, constrain the intermediate steps if you like.)

Finally, a <Future> will recursively await anything that is `await`-able. All concurrent objects built-in to Perl 6 provide an await function that can be used to wait for a value from another thread to become available whtin the current thread. This means that any time a Future encounters an object that can be awaited, it will await that return before continuing.

# GOALS

Why has this module been created? This module's purpose is to create an interface based on <Promise> that has a few features which can make it nicer to work with as a developer. These goals are based upon my own experience working with promise-type tools in other languages, such as Perl 5, JavaScript, and Scala. It does not try to implement a particular interface from that experience, but tries to remain true to idiomatic Perl 6 in style and implementation instead.

Here are the primary goals I had in mind, contrasted with the behavior of <Promise>:

* * A <Future> should have the ability to use chains of callback to handle exceptional conditions. A <Promise> does not call any callbacks if the Promise is broken. To handle an exception, you must do something like nested `start` blocks with the outer start block `await`ing an inner block and catching the exception that may be rethrown.
* * A <Future> should be parameterized by type. A <Promise> may be kept with any kind of value. One advantage of a type-system is that it is self-documenting. By examining the types accepted as parameters or returned, its often possible to infer what a subroutine does. A Promise provides some useful information about the immediate type, but no indication as to what it could become in the future.

# FUTURE STATES

A <Future> has three possible states:

* * **Pending.** A pending Future is one that may either become fulfilled or become rejected. It might also remain pending indefinitely. This corresponds to the Planned state of <Promise>.
* * **Fulfilled.** A fulfilled Future is complete and has a value. This is a stop state and the Future is not able to transition out of this status. This corresponds to the Kept state of <Promise>.
* * **Rejected.** A rejected Future is failed with an exception. This is a stop state and the Future is not able to transition out of this status. This corresponds to the Broken state of <Promise>.

While a particular <Future> object is unable to transition out of a fulfilled or rejected stop state, you can transform the Future using a callback. Callbacks will construct a new future, which can have a different state than the one the callback starts with.

# METHODS

## method awaitable

```
method awaitable(Future:U: $p --> Future:D)

```

This constructs and returns a new <Future> based around the given <Promise> or other awaitable object. The Future will be fulfilled or rejected whenever the underlying Promise or other `await`-able is fulfilled or rejected.

The following is mostly a reiteration of the documentation for `await`, but here's a quick rundown of how each behaves when wrapped in a <Future>.

### Promise

The <Future> will remain pending as long as the <Promise> is Planned. The Future will become fulfilled when the Promise is Kept or rejected when the Promise is broken.

### Channel

The <Future> remains pending until the next value is sent to the underlying <Channel>. At that time, the Future becomes fulfilled with that value. If the Channel is closed before a value is sent, the Future is rejected.

### Supply

The <Future> is held pending until the <Supply> emits all values and is done. The Future will become fulfilled with the final value emitted at that point. If, isntead, the Supply quits, the <Future> becomes rejected.

## method start

```
method start(Future:U: &block --> Future:D)

```

You can think of this as a shortcut for:

```
Future.awaitable(start { ... });

```

The given `&block` will be scheduled to run on the next available thread. Then, this method constructs and returns a <Future> whose outcome will be based upon the outcome of that block. If the block exits normally, the result of the block will become the fulfilled Future value. If, instead, the block throws an exception, the Future is rejected with that exception.

## method immediate

```
method immediate(Future:U: $value --> Future:D)

```

This method constructs and returns a Future that is already fulfilled with the given value.

## method exceptional

```
method exceptional(Future:U: Exception $x --> Future:D)

```

This method constructs and returns a Future that is already rejected with the given <Exception>.

## method is-pending

```
method is-pending(Future:D: --> Bool)

```

Returns True while the <Future> is pending and not yet either fulfilled or rejected. Therefore, the following invariant will always be true:

```
.is-pending ?? !.is-fulfilled && !.is-rejected !! .is-fulfilled || .is-rejected

```

Once this becomes False, it will always be False.

## method is-fulfilled

```
method is-fulfilled(Future:D: --> Bool)

```

Returns True if the <Future> has been fulfilled with a value. Once this becomes True it will always be True.

## method is-rejected

```
method is-rejected(Future:D: --> Bool)

```

Returns True if the <Future> has been rejected with an <Exception>. Once this becomes True it will always be True.

## method then

```
method then(Future:D: *@callbacks --> Future:D)

```

This method constructs and returns a new <Future>. When the original invocant is fulfilled, a callback will be selected based on the outcome of the original Future's fulfillment. For example:

```
my $v = await Future.start({ 41 }).then(
    -> Str $s { $s.Int },
    -> Int $i { $i + 1 },
);
say $v; #> 42

```

The callback with a signature matching the original value will be chosen. Exactly one callback must apply to the value or an exception will be thrown. If multiple callbacks may apply, you should use the `is default` trait to distinguish which is preferred. The goal here is to act as much like a multi-sub as possible. (Though, the exceptions thrown are X::Future::NoMatch and X::Future::Ambiguous rather than the Perl counterparts for multis.)

The outcome of the callback is then used to determine the outcome of the newly constructed <Future>. If the block exits normally, the resulting value will be the fulfilled value of the Future. If the block exits with an exception, that exception will be used for the rejection of that Future.

If the Future is rejected, none of these callbacks are called and the <Future> becomes rejected with the same exception as the original invocant:

```
await Future.start({ die 42 }).then(
    -> Str $s { $s.Int }, # ignored
    -> Int $i { $i + 1 }, # ignored
);

CATCH { .payload.say }
#> 42

```

When going from one <Future> to the next in the `.then()` callback chain, the results of each Future earlier in the chain is treated as a <Capture>. This means that by using Capture objects directly (or, if you prefer, lists or hashes to create Capture-like objects indirectly), you can very nicely chain complex results from one <Future> to the next:

```
Future.start({ \(42, :!beeblebrox) }).then(
    -> $answer, :$beeblebrox = True { ... }
});

```

## method catch

```
method catch(Future:D: *@callbacks --> Future:D)

```

This method constructs and returns a new <Future>. When the original invocant is rejected, a callback will be selected based on teh outcome of the original Future's rejection. For example:

```
my $v = await Future({ die 42 }).then(
    -> X::AdHoc $x { .payload }),
    -> X::IO $x { $x.rethrow }),
);
say $v; #> 42

```

The callback with a signature matching the original Future's rejected Exception value will be chosen. The first matching callback is accepted and it is acceptable for no callback to match (in which case, the returned Future will be rejected with the same exception as the original). The goal is to act as much as possible like a CATCH-block.

The outcome of the callback is used to determine the outcome of the newly constructure <Future>. If the block exits normally, the resulting value will be the fulfilled value of the Future. If the block exits with an exception, that exception will be used for the rejection of that Future.

If the original <Future> is fulfilled, the callbacks will be ignored and the new Future in the chain will be fulfilled with the same value as the previous.

## method constrain

```
method constrain(Future:D: Mu \type --> Future:D)

```

Given a type name, this constructs a new Future constrained to that type. It is most useful in situations where you want to add a type constraint on the end-product but the intermediate steps in the callback chain can be something different:

```
# This example is trivial, but makes the point
sub calculate(Int $i --> Future[Str]) {
    Future.start({
        (1..*).grep(*.is-prime)[$i]
    }).then({ .Str }).constrain(Str);
}

my Future[Str] $p = calculate(10_000_000_000);
say await $p;

```

It constrains the type. It is up to the <Future> to make sure the correct type is actually fulfilled. If the fulfilled type does not match the constraint, the Future is rejected with an X::Future::Mismatch exception.

## method result

```
method result(Future:D: --> Mu)

```

This will return the fulfilled result of the <Future> or throw the <Exception> the future was rejected with. This will block until a value becomes available.

## sub await

```
sub await(Future:D $future --> Mu)

```

This will return the fulfilled result of the <Future> or throw the <Exception> the future was rejected with. This will block until a value becomes available.

# DIAGNOSTICS

Here are the exceptions that are specifically added by this class. Please note that there may be other exceptions thrown by a <Future> that are just standard Perl exceptions. See the documentation of exceptions for Perl and Rakudo, especially regarding exceptions that may be thrown by `await`.

## X::Future

All of the special exceptions that may be thrown by the <Future> itself will implement this base exception.

## X::Future::NoMatch

This is roughly equivalent to X::Multi::NoMatch and occurs when none of the callbacks listed in a callback chain are unable to handle the incoming value.

## X::Future::Ambiguous

This is rougly equivalent to X::Multi::Ambiguous and occurs when more than one callback listed could resolve the callback value. If this could be possible, it is recommended that you add the `is default` trait to one of the callbacks.

## X::Future::Mismatch

This is thrown when the <Future> is fulfilled with a value that does not match the parameterized type constraint of the Future.

### method expected

```
method expected(X::Future::Mismatch:D: --> Mu)

```

Returns the type constraint of the <Future>.

### method got

```
method got(X::Future::Mismatch:D: --> Mu)

```

Returns the value that failed the type constraint.


## dist_zef-raku-community-modules-HTTP-Server-Async.md
[![Actions Status](https://github.com/raku-community-modules/HTTP-Server-Async/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/HTTP-Server-Async/actions)

# NAME

HTTP::Server::Async - Asynchronous Base HTTP Server

# SYNOPSIS

```
use HTTP::Server::Async;

my $s = HTTP::Server::Async.new;

$s.handler:  -> $request, $response {
    $response.headers<Content-Type> = 'text/plain';
    $response.status = 200;
    $response.write("Hello ");
    # keeps a promise in the response and ends the server handler processing
    $response.close("world!");
}

$s.listen(True);

```

# DESCRIPTION

HTTP::Server::Async provides an implementation of an HTTP server, based on the roles provided by `HTTP::Roles`.

It currently handles:

* Parsing Headers
* Chunked Transfer
* Hooks for middleware or route handling
* Simple response handling

It does **not** handle:

* ~~Route handling~~ (See [`HTTP::Server::Router`](https://github.com/tony-o/perl6-http-server-router))
* ~~File transfers~~

# CLASSES

## HTTP::Server::Async

### new

Takes these named arguments to return an instantiated object:

* :port - port to listen on
* :host - IP number to listen on
* :buffered - whether responses should be buffered or not (Bool)

### handler

Any `Callable` passed to this method is registered to be called on every incoming request in the order in which they were registered.

Any registered `Callable` should return `True` to continue processing. A `False` value will discontinue processing of the request. Alternatively a `Promise` can be returned: if the `Promise` is broken then the server will discontinue, if the promise is kept then processing will continue.

The `Callable` will receive two parameters from the server, an `HTTP::Server::Async::Request` and a `HTTP::Server::Async::Response` object. More about the `Response` and `Request` object below.

Note that the server will wait for the request body to be complete before calling `Callable` registered with `handler`.

### middleware

The same as the `handler` except will **NOT** wait for a complete request body. The middleware can hijack the connection by explicitly returning `False` and continuing processing using `$request.connection` to gain control of the socket.

### listen

Starts the server and does **not** block, unless called with a `True` value.

## HTTP::Server::Async::Request

This handles the parsing of an incoming request.

### Attributes

#### method

GET/PUT/POST/etc.

#### headers

hash with Key/value pair containing the header values.

#### uri

Requested resource.

#### version

HTTP/1.X (or whatever was in the request).

#### data

String containing the data included with the request.

## HTTP::Server::Async::Response

Response object, handles writing and closing the socket.

### Attributes

#### buffered

Whether or not the response object should buffer the response and write on close, or write directly to the socket.

#### status

Set the status of the response, uses HTTP status codes. See [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) for more information. Defaults to 200.

#### headers

Hash with response headers to be sent, accessed directly. Modifying these after writing to the socket will have no effect on the response unless the `buffered` is set to True.

### Methods

#### write

Write data to the socket, will call the appropriate method for the socket (`$connection.write` for `Str`s, anything else is `$connection.send`)

#### close

Close takes optional parameter of data to send out. Will call `write` if a parameter is provided. Closes the socket, writes headers if the response is buffered, etc.

# CREDITS

Thanks to ugexe, btyler, jnthn, and timotimo for helping figure out bugs, answer a bunch of questions, etc.

# AUTHOR

Tony O'Dell

# COPYRIGHT AND LICENSE

Copyright 2014 - 2019 Tony O'Dell

Copyright 2020 - 2022 Raku Community

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## -infix-.md
==, infix ⩵

Combined from primary sources listed below.

# [In Operators](#___top "go to top of document")[§](#(Operators)_infix_==,_infix_⩵ "direct link")

See primary documentation
[in context](/language/operators#infix_==,_infix_⩵)
for **infix ==, infix ⩵**.

```raku
multi infix:<==>(Any, Any)
multi infix:<==>(Int:D, Int:D)
multi infix:<==>(Num:D, Num:D)
multi infix:<==>(Rational:D, Rational:D)
multi infix:<==>(Real:D, Real:D)
multi infix:<==>(Complex:D, Complex:D)
multi infix:<==>(Numeric:D, Numeric:D)
```

Numeric equality operator.

Coerces both arguments to [`Numeric`](/type/Numeric) (if necessary); returns `True` if they are equal.

Since Rakudo version 2021.07, ⩵ is an alias for this operator.


## dist_zef-zoss-WebDriver2.md
# WebDriver2

WebDriver level 2 bindings implementing
[W3C's specification](https://www.w3.org/TR/webdriver/).
Current implementation status is
[documented below](#implementation-status).

## Usage

### Using a driver directly

To use a driver directly for all [endpoint commands](#implementation-status), create a
test class that does `WebDriver2::Test::Template`. The test class
will need to specify the browser upon instantiation:

```
use Test;
use WebDriver2::Test::Template;
use WebDriver2::SUT::Tree;

# can be file path or web address
my WebDriver2::SUT::Tree::URL:D $page =
		WebDriver2::SUT::Tree::URL.new: 'file://xt/content/test.html';

class Local does WebDriver2::Test::Template {
	has Bool $!screenshot;

	has Int:D $.plan = 38;
	has Str:D $.name = 'local';
	has Str:D $.description = 'local test';

	# WebDriver2::Test::Template provides method new, which
	#   sets the browser / loads from file if not passed
	#   and instantiates the corresponding driver

	method test {
		$.driver.navigate: $page.Str;

		is $.driver.title, 'test', 'page title';

		ok
				self.element-by-id( 'outer' ) ~~ self.element-by-tag( 'ul' ),
				'same element found different ways';

		my WebDriver2::Command::Element::Locator $by-tag-ul =
				WebDriver2::Command::Element::Locator::Tag-Name.new: 'ul';
		my WebDriver2::Model::Element $el = $.driver.element: $by-tag-ul;
		nok $el ~~ $el.element( $by-tag-ul ), 'different elements';

		my WebDriver2::Command::Element::Locator $locator =
				WebDriver2::Command::Element::Locator::Tag-Name.new: 'li';
		$el = $.driver.element: $locator;
		my Str $outer-li = $el.text;
		my Str $inner-li =
				self.element-by-id( 'inner' ).element( $locator ).text;

		isnt $inner-li, $outer-li, 'inner li != outer li';

		# test continues ...
	}
}

sub MAIN (
	Str $browser?,
	Int:D :$debug = 0
) {
	.execute with Local.new: $browser, :$debug;
}

```

`WebDriver2::Test::Template` calls

```
method init { ... }
method pre-test { ... }
method test { ... }
method post-test { ... }
method close { ... }
method done-testing { done-testing }
method cleanup { ... }

```

when its `execute` method is called.

Before starting into the test code, `$.driver.session` needs
to be called, along with `$.driver.delete-session` after
test code has completed. These two calls are made
automatically during `init` and `close` when doing the
provided role `WebDriver2::Test::Template`.

### Defining a site's pages and the services they provide

A simple page description language is defined in the
[page grammar file](lib/WebDriver2/SUT/Build/Page.rakumod).

For a multi-page site, e.g., with a login page and a
main page with an iframe, in addition to the html
files, a "system under test" definition,
which could optionally be split into multiple `.page`
files, and `.service` definitions are needed.

For example, for

`doc-site.sut`

```
#include 'doc-login.page'
#include 'doc-main.page'

```

`doc-login.html`

```
<html>
	<head><title>start page</title></head>
	<body>
		<form action="doc-main.html">
			<input type="text" id="user" name="user"/>
			<input type="text" id="pass" name="pass"/>
			<button name="k" value="v">log in</button>
		</form>
	</body>
</html>

```

`doc-login.page`

```
page doc-login 'file://relative/path/to/doc-login.html' {
	elemt username id 'user';
	elemt password id 'pass';
	elemt login-button tag-name 'button';
}

```

`doc-login.service`

```
#page: doc-login

username: /username
password: /password
login-button: /login-button

```

`doc-main.html`

```
<html>
	<head><title>simple example</title></head>
	<body>
		<h1>simple example</h1>
		<p id="before">text</p>
		<form><input type="text" value="main-1"/></form>
		<iframe src="doc-frame.html"></iframe>
		<form><input type="text" value="main-2"/></form>
		<p>other content</p>
		<form><input type="text" value="main-3"/></form>
		<form><input type="text" value="main-4"/></form>
		<p id="after">more text</p>
	</body>
</html>

```

`doc-main.page` - with only content we're interested in outlined

```
page doc-main 'file://relative/path/to/doc-main.html' {
	elemt heading tag-name 'h1';
	elemt first-para id 'before';
#include 'doc-frame.page'
list of
#include 'doc-form.page'
	elemt last-para id 'after';
}

```

`doc-main.service`

```
#page: doc-main

heading: /heading
pf: /first-para
iframe: /iframe
form: /form
pl: /last-para

```

`doc-frame.html`

```
<html>
	<head><title>iframe</title></head>
	<body>
		<form><input type="text" value="head"/></form>
		<ul>
			<li>
				<ol>
					<li>Mirzakhani</li>
					<li>Noether</li>
					<li>Oh</li>
				</ol>
			</li>
			<li>
				<ol>
					<li>Delta</li>
					<li>Echo</li>
					<li>Foxtrot</li>
				</ol>
			</li>
			<li>
				<ol>
					<li>apple</li>
					<li>banana</li>
					<li>cantaloupe</li>
				</ol>
			</li>
		</ul>
		<div><form><input type="text" value="foot"/></form></div>
	</body>
</html>

```

`doc-frame.page` - again, only content we're interested in is outlined

```
frame iframe tag-name 'iframe' {
#include 'doc-form.page'
	list of elgrp outer xpath '*/ul/li' {
		list of elemt inner xpath 'ol/li';
	}
	elgrp div tag-name 'div' {
#include 'doc-form.page'
	}
}

```

`doc-frame.service`

```
#page: doc-main

iframe: /iframe

outer: /iframe/outer
inner: /iframe/outer/inner

```

if identical content exists in multiple parts of the SUT ( e.g.,
calendar widgets ), it can be defined once and included in those parts by
specifying a prefix

`doc-form.page`

```
elgrp form xpath 'form' {
	elemt input tag-name 'input';
}

```

`doc-form.service`

```
#page: doc-main

form: /form
input: /form/input

```

script with supporting code:

```
use Test;

use lib <lib t/lib>;

use WebDriver2::Test::Template;
use WebDriver2::Test::Service-Test;
use WebDriver2::SUT::Service::Loader;
use WebDriver2::SUT::Service;
use WebDriver2::SUT::Tree;

class Login-Service does WebDriver2::SUT::Service {
	has Str:D $.name = 'doc-login';

	my IO::Path $html-file = $*CWD.add: <xt content doc-login.html>;

	my WebDriver2::SUT::Tree::URL $url =
			WebDriver2::SUT::Tree::URL.new: 'file://' ~ $html-file.Str;

	submethod BUILD ( WebDriver2::Driver:D :$!driver ) { }

	method log-in ( Str:D $username, Str:D $password ) {
		$!driver.navigate: $url.Str;
		.resolve.send-keys: $username with self.get: 'username';
		.resolve.send-keys: $password with self.get: 'password';
		.resolve.click with self.get: 'login-button';
	}
}

class Main-Service does WebDriver2::SUT::Service {
	has Str:D $.name = 'doc-main';

	submethod BUILD ( WebDriver2::Driver:D :$!driver ) { }

	method question ( --> Str:D ) {
		.resolve.text with self.get: 'question';
	}

	method interesting-text ( --> Str:D ) {
		my Str @text;
		@text.push: .resolve.text with self.get: 'heading';
		@text.push: .resolve.text with self.get: 'pf';
		@text.push: .resolve.text with self.get: 'pl';
		@text.join: "\n";
	}

}

class Form-Service does WebDriver2::SUT::Service {
	has Str:D $.name = 'doc-form';

	submethod BUILD ( WebDriver2::Driver:D :$!driver, Str:D :$!prefix = '' ) { }

	method value ( --> Str:D ) {
		.resolve.value with self.get: 'input';
	}
	method first ( &cb ) {
		for self.get( 'form' ).iterator {
			return self if &cb( self );
		}
		return Form-Service;
	}
	method each ( &action ) {
		for self.get( 'form' ).iterator {
			&action( self );
		}
	}
}

class Frame-Service does WebDriver2::SUT::Service {
	has Str:D $.name = 'doc-frame';

	submethod BUILD ( WebDriver2::Driver:D :$!driver ) { }

	method each-outer ( &cb ) {
		for self.get( 'outer' ).iterator {
			&cb( self );
		}
	}

	method each-inner ( &cb ) {
		for self.get( 'inner' ).iterator {
			&cb( self );
		}
	}

	method item-text ( --> Str:D ) {
		.resolve.text with self.get: 'inner';
	}
}

class Readme-Test
		does WebDriver2::Test::Service-Test
		does WebDriver2::Test::Template
{
	has Login-Service $!ls;
	has Main-Service $!ms;
	has Form-Service $!fs-main;
	has Form-Service $!fs-div;
	has Form-Service $!fs-frame;
	has Frame-Service $!frs;

	submethod BUILD (
			Str   :$!browser,
			Str:D :$!name,
			Str:D :$!description,
			Str:D :$!sut-name,
			Int   :$!plan,
			Int   :$!debug = 0
					 ) { }

	submethod TWEAK (
			Str:D :$sut-name,
			Int   :$debug
					 ) {
		$!sut = WebDriver2::SUT::Build.page: { self.driver.top }, $!sut-name, debug => self.debug;
		$!loader =
				WebDriver2::SUT::Service::Loader.new:
						driver => self.driver,
						:$!browser,
						:$sut-name,
						:$debug;
	}

	method new ( Str $browser is rw, Int $debug = 0 ) {
		my $self = self.bless:
				:$browser,
				:$debug,
				sut-name => 'doc-site',
				name => 'readme example',
				description => 'service / page object example',
				plan => 26;
		$self.init;
		$self.services;
		$self;
	}

	method services {
		$!loader.load-elements: $!ls = Login-Service.new: :$.driver;
		$!loader.load-elements: $!ms = Main-Service.new: :$.driver;

		$!loader.load-elements: $!fs-main = Form-Service.new: :$.driver, prefix => '/';
		$!loader.load-elements: $!fs-frame = Form-Service.new: :$.driver, prefix => '/iframe';
		$!loader.load-elements: $!fs-div = Form-Service.new: :$.driver, prefix => '/iframe/div';

		$!loader.load-elements: $!frs = Frame-Service.new: :$.driver;
	}

	method test {
		$!ls.log-in: 'user', 'pass';

		self.is: 'sub xpath', 'subelement test', .resolve.text with $!ms.get: 'subelement';

		self.is:
				'interesting text',
				q:to /END/.trim,
				simple example
				text
				more text
				END
				$!ms.interesting-text;

		my Str:D @results =
				'Mirzakhani',
				'Noether',
				'Oh',
				'Delta',
				'Echo',
				'Foxtrot',
				'apple',
				'banana',
				'cantaloupe',
				;
		my Int $els = 9;
		my Bool:D $list-seen = False;
		$!frs.each-outer: {
			$list-seen = True;
			self.is: "correct number of elements left", $els, @results.elems;
			$!frs.each-inner: {
				self.is: "correct inner element : @results[0]", @results.shift,
						.item-text;
			}
			$els -= 3;
		}
		self.ok: 'outer', $list-seen;
		self.is: '$els decremented', 0, $els;
		self.is: '@results empty', 0, @results.elems;

		@results = 'main-1', 'main-2', 'main-3', 'main-4';

		$!fs-main.each: { self.is: 'correct form element', @results.shift, .value };
		self.is: '@results empty', 0, @results.elems;

		self.is: 'first frame form is head', 'head', $!fs-frame.value;
		self.is: 'main page form', 'main-1', $!fs-main.first( { True; } ).value;
		self.is: 'final frame form is foot', 'foot', $!fs-div.value;
	}
}

sub MAIN(
		Str:D $browser is copy = 'chrome',
		Int :$debug = 0
) {
	.execute with Readme-Test.new: $browser, $debug;
}

```

Extended examples can be seen in the `xt/02-driver` (direct driver use)
and the `xt/03-service` (page definition and service use) subdirectories, which
use resources from `xt/content` and `xt/def`.

## HTTP::UserAgent

A minor fork of HTTP::UserAgent is provided under the
WebDriver2 directory. Please see its license:
<LICENSE-HTTP-UserAgent>.

The changes are:

1. fix content length (geckodriver does not gracefully handle
   incorrect content lengths)
2. increase amount of info logged (originally capped at 300
   characters per entry)

## TODO

* cover all implemented endpoints with unit tests
* add POD
* implement the rest of the endpoints
* page and service object features

### Feedback

Suggestions, design recommendations, and feature requests
welcome.

### Implementation Status

|  | Windows | | | MacOS |  |
| --- | --- | --- | --- | --- | --- |
| endpoint | chrome | edge | firefox | safari | method |
| new session | X | X | X | X | `$driver.session` |
| delete session | X | X | X | X | `$driver.delete-session` |
| status | X | X | X | X | `$driver.status` |
| get timeouts |  |  |  |  |  |
| set timeouts | X | X | X | X | `$driver.timeouts ( Int $script, Int $page-load, Int $implicit )` |
| navigate to | X | X | X | X | `$driver.navigate ( Str $url )` |
| get current url | X | X | X | X | `$driver.url` |
| back | X | X | X | X | `$driver.back` |
| forward | X | X | X | X | `$driver.forward` |
| refresh | X | X | X | X | `$driver.refresh` |
| get title | X | X | X | X | `$driver.title` |
| get window handle | X | X | X | X | `$driver.window-handle` |
| close window | X | X | X | X | `$driver.close-window` |
| switch to window | X | X | X | X | `$driver.switch-to-window ( $handle )` |
| get window handles | X | X | X | X | `$driver.window-handles` |
| new window |  |  |  |  |  |
| switch to frame | X | X | X | X | `$driver.switch-to ( Int $frame-id )` `$frame-element.switch-to` |
| switch to parent frame | X | X | X | X | `$driver.switch-to-parent` `$element.switch-to-parent` |
| get window rect |  |  |  |  |  |
| set window rect | X | X | X | X | `$driver.set-window-rect ( Int $width, Int $height, Int $x, Int $y )` |
| maximize window |  |  |  |  | `$driver.maximize-window` |
| minimize window |  |  |  |  |  |
| fullscreen window |  |  |  |  |  |
| get active element | X | X | X | X | `$driver.active` |
| get element shadow root |  |  |  |  |  |
| find element | X | X | X | X | `$driver.element ( Locator $loc )` |
| find elements | X | X | X | X | `$driver.elements ( Locator $loc )` |
| find element from element | X | X | X | X | `$element.element ( Locator $loc )` |
| find elements from element | X | X | X | X | `$element.elements ( Locator $loc )` |
| find element from shadow root |  |  |  |  |  |
| find elements from shadow root |  |  |  |  |  |
| is element selected | X | X | X | X | `$element.selected` |
| get element attribute | X | X | X | X | `$element.attribute` |
| get element property | X | X | X | X | `$element.property` |
| get element css value | X | X | X | X | `$element.css-value ( Str $css-prop )` |
| get element text | X | X | X | X | `$element.text` |
| get element tag name | X | X | X | X | `$element.tag-name` |
| get element rect |  |  |  |  |  |
| is element enabled | X | X | X | X | `$element.enabled` |
| get computed role |  |  |  |  |  |
| get computed label |  |  |  |  |  |
| element click | X | X | X | X | `$element.click` |
| element clear | X | X | X | X | `$element.clear` |
| element send keys | / | / | / | / | `$element.send-keys ( $text )` |
| get page source |  |  |  |  |  |
| execute script | X | X | X | X | `$driver.execute-script ( Str $scr, @args )` |
| execute async script |  |  |  |  |  |
| get all cookies |  |  |  |  |  |
| get named cookie |  |  |  |  |  |
| add cookie |  |  |  |  |  |
| delete cookie |  |  |  |  |  |
| delete all cookies |  |  |  |  |  |
| perform actions |  |  |  |  |  |
| release actions |  |  |  |  |  |
| dismiss alert | X | X | X | X | `$driver.dismiss-alert` |
| accept alert | X | X | X | X | `$driver.accept-alert` |
| get alert text | X | X | X | X | `$driver.alert-text` |
| send alert text | X | X | X | X | `$driver.send-alert-text ( Str $text )` |
| take screenshot | X | X | X | X | `$driver.screenshot` |
| take element screenshot | X | X | X | X | `$element.screenshot` |
| print page |  |  |  |  |  |
| displayed ( optional endpoint ) | X | X | X | ! apple does not implement | `$element.displayed` |


## dist_github-zengargoyle-Text-Fortune.md
[![Build Status](https://travis-ci.org/zengargoyle/Text-Fortune.svg?branch=master)](https://travis-ci.org/zengargoyle/Text-Fortune)

# NAME

Text::Fortune - print a random adage, fortune(6), strfile(1)

# SYNOPSIS

```
use Text::Fortune;

# Random fortune from 'fortunefile' & 'fortunefile.dat' -- fortune(6)
my $fortune = Text::Fortune::File.new( path => $fortunefile );
say $fortune.random;

# Generate 'fortunefile.dat' from 'fortunefile' -- strfile(1)
my $datfile = $fortunefile ~ '.dat';
$datafile.IO.open(:w).write(
  Text::Fortune::Index.new.load-fortune( $fortunefile.IO.path )
);

```

# DESCRIPTION

Text::Fortune is a minimal implementation for implementing the fortune(6) and strfile(1) progams, with functions for generating a 'fortunes.dat' file from a 'fortunes' file (strfile(1)) and for retrieving a random fortune (fortune(6)).

# COPYRIGHT AND LICENSE

Copyright 2015 zengargoyle [zengargoyle@gmail.com](mailto:zengargoyle@gmail.com)

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## functions.md
## Chunk 1 of 2
Functions

Functions and functional programming in Raku

Routines are one of the means Raku has to reuse code. They come in several forms, most notably [`Method`](/type/Method)s, which belong in classes and roles and are associated with an object; and functions (also called *subroutines* or [`Sub`](/type/Sub)s, for short), which can be called independently of objects.

Subroutines default to lexical (`my`) scoping, and calls to them are generally resolved at compile time.

Subroutines can have a [`Signature`](/type/Signature), also called *parameter list*, which specifies which, if any, arguments the signature expects. It can specify (or leave open) both the number and types of arguments, and the return value.

Introspection on subroutines is provided via [`Routine`](/type/Routine).

# [Defining/Creating/Using functions](#Functions "go to top of document")[§](#Defining/Creating/Using_functions "direct link")

## [Subroutines](#Functions "go to top of document")[§](#Subroutines "direct link")

The basic way to create a subroutine is to use the `sub` declarator followed by an optional [identifier](/language/syntax#Identifiers):

```raku
sub my-func { say "Look ma, no args!" }
my-func;
```

The sub declarator returns a value of type [`Sub`](/type/Sub) that can be stored in any container:

```raku
my &c = sub { say "Look ma, no name!" }
c;     # OUTPUT: «Look ma, no name!␤»

my Any:D $f = sub { say 'Still nameless...' }
$f();  # OUTPUT: «Still nameless...␤»

my Code \a = sub { say ‚raw containers don't implement postcircumfix:<( )>‘ };
a.();  # OUTPUT: «raw containers don't implement postcircumfix:<( )>␤»
```

The declarator `sub` will declare a new name in the current scope at compile time. As such, any indirection has to be resolved at compile time:

```raku
constant aname = 'foo';
sub ::(aname) { say 'oi‽' };
foo;
```

This will become more useful once macros are added to Raku.

To have the subroutine take arguments, a [`Signature`](/type/Signature) goes between the subroutine's name and its body, in parentheses:

```raku
sub exclaim ($phrase) {
    say $phrase ~ "!!!!"
}
exclaim "Howdy, World";

```

By default, subroutines are [lexically scoped](/syntax/my). That is, `sub foo {...}` is the same as `my sub foo {...}` and is only defined within the current scope.

```raku
sub escape($str) {
    # Puts a slash before non-alphanumeric characters
    S:g[<-alpha -digit>] = "\\$/" given $str
}

say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»

{
    sub escape($str) {
        # Writes each non-alphanumeric character in its hexadecimal escape
        S:g[<-alpha -digit>] = "\\x[{ $/.ord.base(16) }]" given $str
    }

    say escape 'foo#bar?' # OUTPUT: «foo\x[23]bar\x[3F]␤»
}

# Back to original escape function
say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»

```

Subroutines don't have to be named. If unnamed, they're called *anonymous* subroutines.

```raku
say sub ($a, $b) { $a ** 2 + $b ** 2 }(3, 4) # OUTPUT: «25␤»
```

But in this case, it's often desirable to use the more succinct [`Block`](/type/Block) syntax. Subroutines and blocks can be called in place, as in the example above.

```raku
say -> $a, $b { $a ** 2 + $b ** 2 }(3, 4)    # OUTPUT: «25␤»
```

Or even

```raku
say { $^a ** 2 + $^b ** 2 }(3, 4)            # OUTPUT: «25␤»
```

## [Blocks and lambdas](#Functions "go to top of document")[§](#Blocks_and_lambdas "direct link")

Whenever you see something like `{ $_ + 42 }`, `-> $a, $b { $a ** $b }`, or `{ $^text.indent($:spaces) }`, that's [`Block`](/type/Block) syntax; the `->` is considered also part of the block. Statements such as `if`, `for`, `while` are followed by these kind of blocks.

```raku
for 1, 2, 3, 4 -> $a, $b {
    say $a ~ $b;
}
# OUTPUT: «12␤34␤»
```

They can also be used on their own as anonymous blocks of code.

```raku
say { $^a ** 2 + $^b ** 2}(3, 4) # OUTPUT: «25␤»
```

Please note that this implies that, despite the fact that statements such as `if` do not define a topic variable, they actually can:

```raku
my $foo = 33;
if $foo ** 33 -> $a {
    say "$a is not null"; #
} # OUTPUT: «129110040087761027839616029934664535539337183380513 is not null␤»

```

For block syntax details, see the documentation for the [`Block`](/type/Block) type.

## [Signatures](#Functions "go to top of document")[§](#Signatures "direct link")

The parameters that a function accepts are described in its *signature*.

```raku
sub format(Str $s) { ... }
-> $a, $b { ... }

```

Details about the syntax and use of signatures can be found in the [documentation on the `Signature` class](/type/Signature).

### [Automatic signatures](#Functions "go to top of document")[§](#Automatic_signatures "direct link")

If no signature is provided but either of the two automatic variables `@_` or `%_` are used in the function body, a signature with `*@_` or `*%_` will be generated. Both automatic variables can be used at the same time.

```raku
sub s { say @_, %_ };
say &s.signature # OUTPUT: «(*@_, *%_)␤»
```

## [Arguments](#Functions "go to top of document")[§](#Arguments "direct link")

Arguments are supplied as a comma separated list. To disambiguate nested calls, use parentheses:

```raku
sub f(&c){ c() * 2 }; # call the function reference c with empty parameter list
sub g($p){ $p - 2 };
say(g(42), 45);       # pass only 42 to g()
```

When calling a function, positional arguments should be supplied in the same order as the function's signature. Named arguments may be supplied in any order, but it's considered good form to place named arguments after positional arguments. Inside the argument list of a function call, some special syntax is supported:

```raku
sub f(|c){};
f :named(35);     # A named argument (in "adverb" form)
f named => 35;    # Also a named argument
f :35named;       # A named argument using abbreviated adverb form
f 'named' => 35;  # Not a named argument, a Pair in a positional argument
f 'hi', :1x, :2y; # Positional and named arguments
my \c = <a b c>.Capture;
f |c;             # Merge the contents of Capture $c as if they were supplied
```

Arguments passed to a function are conceptually first collected in a [`Capture`](/type/Capture) container. Details about the syntax and use of these containers can be found in [`Capture`](/type/Capture)'s documentation.

When using named arguments, note that normal list "pair-chaining" allows one to skip commas between named arguments.

```raku
sub f(|c){};
f :dest</tmp/foo> :src</tmp/bar> :lines(512);
f :32x :50y :110z;   # This flavor of "adverb" works, too
f :a:b:c;            # The spaces are also optional.
```

If positional arguments are also passed, then either they must be passed within parentheses placed *immediately* after the function's name or the comma after the last positional argument must be kept when chaining named arguments in abbreviated adverb form. The spaces between chained named arguments and the list of positional arguments is optional.

```raku
sub p($x, $y, :$translate, :$rotate) {};
p(1, 1, :translate, :rotate); # normal way
p 1, 1, :translate, :rotate;  # also normal way

p(1, 1) :translate  :rotate;  # parentheses + chained named arguments
p(1, 1) :translate:rotate;
p(1, 1):translate:rotate;

p 1, 1, :translate  :rotate;  # dangling comma + chained named arguments
p 1, 1, :translate:rotate;
p 1, 1,:translate:rotate;
```

## [Return values](#Functions "go to top of document")[§](#Return_values "direct link")

Any [`Block`](/type/Block) or [`Routine`](/type/Routine) will provide the value of its last expression as a return value to the caller. If either [return](/language/control#return) or [return-rw](/language/control#return-rw) is called, then its parameter, if any, will become the return value. The default return value is [`Nil`](/type/Nil).

```raku
sub a { 42 };
sub b { say a };
sub c { };
b;     # OUTPUT: «42␤»
say c; # OUTPUT: «Nil␤»
```

Multiple return values are returned as a list or by creating a [`Capture`](/type/Capture). Destructuring can be used to untangle multiple return values.

```raku
sub a { 42, 'answer' };
put a.raku;
# OUTPUT: «(42, "answer")␤»

my ($n, $s) = a;
put [$s, $n];
# OUTPUT: «answer 42␤»

sub b { <a b c>.Capture };
put b.raku;
# OUTPUT: «\("a", "b", "c")␤»
```

## [Return type constraints](#Functions "go to top of document")[§](#Return_type_constraints "direct link")

Raku has many ways to specify a function's return type:

```raku
sub foo(--> Int)      {}; say &foo.returns; # OUTPUT: «(Int)␤»

```

```raku
sub foo() returns Int {}; say &foo.returns; # OUTPUT: «(Int)␤»

```

```raku
sub foo() of Int      {}; say &foo.returns; # OUTPUT: «(Int)␤»

```

```raku
my Int sub foo()      {}; say &foo.returns; # OUTPUT: «(Int)␤»

```

Attempting to return values of another type will cause a compilation error.

```raku
sub foo() returns Int { "a"; }; foo; # Type check fails

```

`returns` and `of` are equivalent, and both take only a Type since they are declaring a trait of the [`Callable`](/type/Callable). The last declaration is, in fact, a type declaration, which obviously can take only a type. In the other hand, `-->` can take either undefined or definite values.

Note that [`Nil`](/type/Nil) and [`Failure`](/type/Failure) are exempt from return type constraints and can be returned from any routine, regardless of its constraint:

```raku
sub foo() returns Int { fail   }; foo; # Failure returned
sub bar() returns Int { return }; bar; # Nil returned

```

## [Multi-dispatch](#Functions "go to top of document")[§](#Multi-dispatch "direct link")

Raku allows for writing several routines with the same name but different signatures. When the routine is called by name, the runtime environment determines the proper *candidate* and invokes it.

Each candidate is declared with the `multi` keyword. Dispatch happens depending on the parameter [arity](/type/Code#method_arity) (number), type and name; and under some circumstances the order of the multi declarations. Consider the following example:

```raku
# version 1
multi happy-birthday( $name ) {
    say "Happy Birthday $name !";
}

# version 2
multi happy-birthday( $name, $age ) {
    say "Happy {$age}th Birthday $name !";
}

# version 3
multi happy-birthday( :$name, :$age, :$title  = 'Mr' ) {
    say "Happy {$age}th Birthday $title $name !";
}

# calls version 1 (arity)
happy-birthday 'Larry';                        # OUTPUT: «Happy Birthday Larry !␤»
# calls version 2 (arity)
happy-birthday 'Luca', 40;                     # OUTPUT: «Happy 40th Birthday Luca !␤»
# calls version 3
# (named arguments win against arity)
happy-birthday( age => '50', name => 'John' ); # OUTPUT: «Happy 50th Birthday Mr John !␤»
# calls version 2 (arity)
happy-birthday( 'Jack', 25 );                  # OUTPUT: «Happy 25th Birthday Jack !␤»

```

The first two versions of the `happy-birthday` sub differs only in the arity (number of arguments), while the third version uses named arguments and is chosen only when named arguments are used, even if the arity is the same of another `multi` candidate.

When two sub have the same arity, the type of the arguments drive the dispatch; when there are named arguments they drive the dispatch even when their type is the same as another candidate:

```raku
multi happy-birthday( Str $name, Int $age ) {
    say "Happy {$age}th Birthday $name !";
}

multi happy-birthday( Str $name, Str $title ) {
    say "Happy Birthday $title $name !";
}

multi happy-birthday( Str :$name, Int :$age ) {
    say "Happy Birthday $name, you turned $age !";
}

happy-birthday 'Luca', 40;                 # OUTPUT: «Happy 40th Birthday Luca !␤»
happy-birthday 'Luca', 'Mr';               # OUTPUT: «Happy Birthday Mr Luca !␤»
happy-birthday age => 40, name => 'Luca';  # OUTPUT: «Happy Birthday Luca, you turned 40 !␤»

```

Named parameters participate in the dispatch even if they are not provided in the call. Therefore a multi candidate with named parameters will be given precedence.

For more information about type constraints see the documentation on [`Signature` literals](/language/signatures#Type_constraints).

```raku
multi as-json(Bool $d) { $d ?? 'true' !! 'false'; }
multi as-json(Real $d) { ~$d }
multi as-json(@d)      { sprintf '[%s]', @d.map(&as-json).join(', ') }

say as-json( True );                        # OUTPUT: «true␤»
say as-json( 10.3 );                        # OUTPUT: «10.3␤»
say as-json( [ True, 10.3, False, 24 ] );   # OUTPUT: «[true, 10.3, false, 24]␤»
```

For some signature differences (notably when using a where clause or a subset) the order of definition of the multi methods or subs is used, evaluating each possibility in turn. See [multi resolution by order of definition](/language/functions#multi_resolution_by_order_of_definition) below for examples.

`multi` without any specific routine type always defaults to a `sub`, but you can use it on methods as well. The candidates are all the multi methods of the object:

```raku
class Congrats {
    multi method congratulate($reason, $name) {
        say "Hooray for your $reason, $name";
    }
}

role BirthdayCongrats {
    multi method congratulate('birthday', $name) {
        say "Happy birthday, $name";
    }
    multi method congratulate('birthday', $name, $age) {
        say "Happy {$age}th birthday, $name";
    }
}

my $congrats = Congrats.new does BirthdayCongrats;

$congrats.congratulate('promotion','Cindy'); # OUTPUT: «Hooray for your promotion, Cindy␤»
$congrats.congratulate('birthday','Bob');    # OUTPUT: «Happy birthday, Bob␤»
```

Unlike `sub`, if you use named parameters with multi methods, the parameters must be required parameters to behave as expected.

Please note that a non-multi sub or operator will hide multi candidates of the same name in any parent scope or child scope. The same is true for imported non-multi candidates.

Multi-dispatch can also work on parameter traits, with routines with `is rw` parameters having a higher priority than those that do not:

```raku
proto þoo (|) {*}
multi þoo( $ðar is rw ) { $ðar = 42 }
multi þoo( $ðar ) { $ðar + 42 }
my $bar = 7;
say þoo($bar); # OUTPUT: «42␤»

```

### [proto](#Functions "go to top of document")[§](#proto "direct link")

`proto` is a way to formally declare commonalities between `multi` candidates. It acts as a wrapper that can validate but not modify arguments. Consider this basic example:

```raku
proto congratulate(Str $reason, Str $name, |) {*}
multi congratulate($reason, $name) {
   say "Hooray for your $reason, $name";
}
multi congratulate($reason, $name, Int $rank) {
   say "Hooray for your $reason, $name -- got rank $rank!";
}

congratulate('being a cool number', 'Fred');     # OK
congratulate('being a cool number', 'Fred', 42); # OK
```

```raku
congratulate('being a cool number', 42);         # Proto match error

```

The proto insists that all `multi congratulate` subs conform to the basic signature of two strings, optionally followed by further parameters. The `|` is an un-named [`Capture`](/type/Capture) parameter, and allows a `multi` to take additional arguments. The first two calls succeed, but the third fails (at compile time) because `42` doesn't match [`Str`](/type/Str).

```raku
say &congratulate.signature # OUTPUT: «(Str $reason, Str $name, | is raw)␤»

```

You can give the `proto` a function body, and place the `{*}` (note there is no whitespace inside the curly braces) where you want the dispatch to be done. This can be useful when you have a "hole" in your routine that gives it different behavior depending on the arguments given:

```raku
# attempts to notify someone -- False if unsuccessful
proto notify(Str $user, Str $msg) {
   my \hour = DateTime.now.hour;
   if 8 < hour < 22 {
      return {*};
   } else {
      # we can't notify someone when they might be sleeping
      return False;
   }
}
```

Since `proto` is a wrapper for `multi` candidates, the signatures of the routine's `multi` candidates do not necessarily have to match that of the `proto`; arguments of `multi` candidates may have subtypes of those of the `proto`, and the return types of the `multi` candidates may be entirely different from that of the `proto`. Using differing types like this is especially useful when giving `proto` a function body:

```raku
enum DebugType <LOG WARNING ERROR>;

#|[ Prints a message to stderr with a color-coded key. ]
proto debug(DebugType:D $type, Str:D $message --> Bool:_) {
    note sprintf qb/\e[1;%dm[%s]\e[0m %s/, {*}, $type.key, $message
}
multi debug(LOG;; Str:D --> 32)     { }
multi debug(WARNING;; Str:D --> 33) { }
multi debug(ERROR;; Str:D --> 31)   { }

```

`{*}` always dispatches to candidates with the parameters it's called with. Parameter defaults and type coercions will work but are not passed on.

```raku
proto mistake-proto(Str() $str, Int $number = 42) {*}
multi mistake-proto($str, $number) { say $str.^name }
mistake-proto(7, 42);  # OUTPUT: «Int␤» -- not passed on

```

```raku
mistake-proto('test'); # fails -- not passed on

```

A longer example using `proto` for methods shows how to extract common functionality into a proto method.

```raku
class NewClass {
    has $.debug is rw = False;
    has $.value is rw = 'Initial value';
    proto method handle( | ) {
        note "before value is ｢$.value｣" if $.debug;
        {*}
        note "after value is ｢$.value｣" if $.debug;
    }
    multi method handle(Str $s) {
        $.value = $s;
        say 'in string'
    }
    multi method handle(Positional $s) {
        $.value = $s[0];
        say 'in positional'
    }
    multi method handle( $a, $b ) {
        $.value = "$a is looking askance at $b";
        say 'with more than one value'
    }
}
my NewClass $x .= new;
$x.handle('hello world');
$x.handle(<hello world>);
$x.debug = True;
$x.handle('hello world');
$x.handle(<hello world>);
$x.handle('Claire', 'John');
# OUTPUT:
# in string
# in positional
# before value is ｢hello｣
# in string
# after value is ｢hello world｣
# before value is ｢hello world｣
# in positional
# after value is ｢hello｣
# before value is ｢hello｣
# with more than one value
# after value is ｢Claire is looking askance at John｣

```

### [only](#Functions "go to top of document")[§](#only "direct link")

The `only` keyword preceding `sub` or `method` indicates that it will be the only function with that name that inhabits a given namespace.

```raku
only sub you () {"Can make all the world seem right"};
```

This will make other declarations in the same namespace, such as

```raku
sub you ( $can ) { "Make the darkness bright" }
```

fail with an exception of type [`X::Redeclaration`](/type/X/Redeclaration). `only` is the default value for all subs; in the case above, not declaring the first subroutine as `only` will yield exactly the same error; however, nothing prevents future developers from declaring a proto and preceding the names with `multi`. Using `only` before a routine is a [defensive programming](https://en.wikipedia.org/wiki/Defensive_programming) feature that declares the intention of not having routines with the same name declared in the same namespace in the future.

｢text｣ without highlighting

```

```

(exit code 1)
===SORRY!=== Error while compiling /tmp/only-redeclaration.raku
Redeclaration of routine 'you' (did you mean to declare a multi-sub?)
at /tmp/only-redeclaration.raku:3
------> <BOL>⏏<EOL>

```

```

Anonymous subs cannot be declared `only`. `only sub {}` will throw an error of type, surprisingly, [`X::Anon::Multi`](/type/X/Anon/Multi).

### [multi resolution by order of definition](#Functions "go to top of document")[§](#multi_resolution_by_order_of_definition "direct link")

When the breakdown by parameter type is not enough to find an unambiguous match, there are some different tie breakers that may be evaluated in order of declaration of the methods or subs: these include where clauses and subsets, named parameters, and signature unpacks.

In this code example, two multi subs are distinguished only by where clauses where there's one ambiguous case that might pass either of them, the value 4. In this case, which ever multi sub is defined first wins:

```raku
{
  multi check_range ( Int $n where {$_ > 3} ) {
      return "over 3";
  };
  multi check_range ( Int $n where {$_ < 5} ) {
      return "under 5";
  };
  say check_range(4);  # OUTPUT: over 3
}
{
  multi check_range ( Int $n where {$_ < 5} ) {
      return "under 5";
  };
  multi check_range ( Int $n where {$_ > 3} ) {
      return "over 3";
  };
  say check_range(4);  # OUTPUT: under 5
}

```

In the following example, three subsets are used to restrict strings to certain allowed values, where there are overlaps between all three:

```raku
subset Monster  of Str where { $_ eq any( <godzilla gammera ghidora> ) };
subset Hero     of Str where { $_ eq any( <godzilla ultraman inframan> ) };
subset Knockoff of Str where { $_ eq any( <gammera inframan thorndike> ) };

{
    multi speak (Monster $name) {
        say "The monster, $name roars!";
    }
    multi speak (Hero $name) {
        say "The hero, $name shouts!";
    }
    multi speak (Knockoff $name) {
        say "The knockoff, $name, slinks away...";
    }
    speak('godzilla');     # OUTPUT: The monster, godzilla roars!
    speak('gammera');      # OUTPUT: The monster, gammera roars!
    speak('inframan');     # OUTPUT: The hero, inframan shouts!
}

```

Note that here 'godzilla' is treated as Monster, not as Hero, because the Monster multi comes first; and neither 'gammera' or 'inframan' are treated as Knockoff, because that multi comes last.

It should be noted that the order of definition is the order in which Raku sees them, which might not be easy to discern if, for example, the multi subs were imported from different modules. As the organization of a code base becomes more complex, object classes may scale better than using subsets as types, as in this example.

# [Conventions and idioms](#Functions "go to top of document")[§](#Conventions_and_idioms "direct link")

While the dispatch system described above provides a lot of flexibility, there are some conventions that most internal functions, and those in many modules, will follow.

## [Slurpy conventions](#Functions "go to top of document")[§](#Slurpy_conventions "direct link")

Perhaps the most important one of these conventions is the way slurpy list arguments are handled. Most of the time, functions will not automatically flatten slurpy lists. The rare exceptions are those functions that don't have a reasonable behavior on lists of lists (e.g., [chrs](/routine/chrs)) or where there is a conflict with an established idiom (e.g., [pop](/routine/pop) being the inverse of [push](/routine/push)).

If you wish to match this look and feel, any [`Iterable`](/type/Iterable) argument must be broken out element-by-element using a `**@` slurpy, with two nuances:

* An [`Iterable`](/type/Iterable) inside a [Scalar container](/language/containers#Scalar_containers) doesn't count.
* [`List`](/type/List)s created with a [`,`](/routine/,) at the top level only count as one [`Iterable`](/type/Iterable).

This can be achieved by using a slurpy with a [`+`](/language/signatures#Parameter_traits_and_modifiers) or `+@` instead of `**@`:

```raku
sub grab(+@a) { "grab $_".say for @a }
```

which is shorthand for something very close to:

```raku
multi grab(**@a) { "grab $_".say for @a }
multi grab(\a) {
    a ~~ Iterable and a.VAR !~~ Scalar ?? nextwith(|a) !! nextwith(a,)
}
```

This results in the following behavior, which is known as the *"single argument rule"* and is important to understand when invoking slurpy functions:

```raku
grab(1, 2);      # OUTPUT: «grab 1␤grab 2␤»
grab((1, 2));    # OUTPUT: «grab 1␤grab 2␤»
grab($(1, 2));   # OUTPUT: «grab 1 2␤»
grab((1, 2), 3); # OUTPUT: «grab 1 2␤grab 3␤»

```

This also makes user-requested flattening feel consistent whether there is one sublist, or many:

```raku
grab(flat (1, 2), (3, 4));   # OUTPUT: «grab 1␤grab 2␤grab 3␤grab 4␤»
grab(flat $(1, 2), $(3, 4)); # OUTPUT: «grab 1 2␤grab 3 4␤»
grab(flat (1, 2));           # OUTPUT: «grab 1␤grab 2␤»
grab(flat $(1, 2));          # OUTPUT: «grab 1␤grab 2␤»

```

It's worth noting that mixing binding and sigilless variables in these cases requires a bit of finesse, because there is no [`Scalar`](/type/Scalar) intermediary used during binding.

```raku
my $a = (1, 2);  # Normal assignment, equivalent to $(1, 2)
grab($a);        # OUTPUT: «grab 1 2␤»
my $b := (1, 2); # Binding, $b links directly to a bare (1, 2)
grab($b);        # OUTPUT: «grab 1␤grab 2␤»
my \c = (1, 2);  # Sigilless variables always bind, even with '='
grab(c);         # OUTPUT: «grab 1␤grab 2␤»

```

See the [documentation of the `list` subroutine](/type/List#routine_list) for more examples of how to use a routine that adheres to the single argument rule.

# [Functions are first-class objects](#Functions "go to top of document")[§](#Functions_are_first-class_objects "direct link")

Functions and other code objects can be passed around as values, just like any other object.

There are several ways to get hold of a code object. You can assign it to a variable at the point of declaration:

```raku
my $square = sub (Numeric $x) { $x * $x }
# and then use it:
say $square(6);    # OUTPUT: «36␤»
```

Or you can reference an existing named function by using the `&`-sigil in front of it.

```raku
sub square($x) { $x * $x };

# get hold of a reference to the function:
my $func = &square
```

This is very useful for *higher order functions*, that is, functions that take other functions as input. A simple one is [map](/type/List#routine_map), which applies a function to each input element:

```raku
sub square($x) { $x * $x };
my @squared = map &square,  1..5;
say join ', ', @squared;        # OUTPUT: «1, 4, 9, 16, 25␤»
```

You can use the same for operators, except that in that case the name with which they have been declared, using `infix:`, must be used:

```raku
my $exp := &infix:<**>; say $exp(7,3); # OUTPUT: «343␤»
```

This can be done even in cases where operators have been *auto-generated*, for instance in this case where `XX` is the metaoperator `X` applied to the `X` operator.

```raku
my $XX := &infix:<XX>; say $XX( [1,(2,3)] , [(4,5),6]  );
# OUTPUT: «(((1 (4 5))) ((1 6)) (((2 3) (4 5))) (((2 3) 6)))␤»
```

Baseline is that, in case of operators, you don't really need to worry about the actual way they were defined, just use the `&infix< >` to grab a pointer to them.

## [Infix form](#Functions "go to top of document")[§](#Infix_form "direct link")

To call a subroutine with 2 arguments like an infix operator, use a subroutine reference surrounded by `[` and `]`.

```raku
sub plus { $^a + $^b };
say 21 [&plus] 21;
# OUTPUT: «42␤»
```

## [Closures](#Functions "go to top of document")[§](#Closures "direct link")

All code objects in Raku are *closures*, which means they can reference lexical variables from an outer scope.

```raku
sub generate-sub($x) {
    my $y = 2 * $x;
    return sub { say $y };
    #      ^^^^^^^^^^^^^^  inner sub, uses $y
}
my $generated = generate-sub(21);
$generated(); # OUTPUT: «42␤»
```

Here, `$y` is a lexical variable inside `generate-sub`, and the inner subroutine that is returned uses it. By the time that inner sub is called, `generate-sub` has already exited. Yet the inner sub can still use `$y`, because it *closed* over the variable.

Another closure example is the use of [map](/type/List#routine_map) to multiply a list of numbers:

```raku
my $multiply-by = 5;
say join ', ', map { $_ * $multiply-by }, 1..5;     # OUTPUT: «5, 10, 15, 20, 25␤»
```

Here, the block passed to `map` references the variable `$multiply-by` from the outer scope, making the block a closure.

Languages without closures cannot easily provide higher-order functions that are as easy to use and powerful as `map`.

## [Routines](#Functions "go to top of document")[§](#Routines "direct link")

Routines are code objects that conform to the type [`Routine`](/type/Routine), most notably [`Sub`](/type/Sub), [`Method`](/type/Method), [`Regex`](/type/Regex) and [`Submethod`](/type/Submethod).

They carry extra functionality in addition to what a [`Block`](/type/Block) supplies: they can come as [multis](#Multi-dispatch), you can [wrap](/type/Routine#method_wrap) them, and exit early with `return`:

```raku
my $keywords = set <if for unless while>;

sub has-keyword(*@words) {
    for @words -> $word {
        return True if $word (elem) $keywords;
    }
    False;
}

say has-keyword 'not', 'one', 'here';       # OUTPUT: «False␤»
say has-keyword 'but', 'here', 'for';       # OUTPUT: «True␤»
```

Here, `return` doesn't just leave the block inside which it was called, but the whole routine. In general, blocks are transparent to `return`, they attach to the outermost routine.

Routines can be inlined and as such provide an obstacle for wrapping. Use the pragma `use soft;` to prevent inlining to allow wrapping at runtime.

```


## functions.md
## Chunk 2 of 2
raku
sub testee(Int $i, Str $s){
    rand.Rat * $i ~ $s;
}

sub wrap-to-debug(&c){
    say "wrapping {&c.name} with arguments {&c.signature.raku}";
    &c.wrap: sub (|args){
        note "calling {&c.name} with {args.gist}";
        my \ret-val := callwith(|args);
        note "returned from {&c.name} with return value {ret-val.raku}";
        ret-val
    }
}

my $testee-handler = wrap-to-debug(&testee);
# OUTPUT: «wrapping testee with arguments :(Int $i, Str $s)␤»

say testee(10, "ten");
# OUTPUT: «calling testee with \(10, "ten")␤returned from testee with return value "6.151190ten"␤6.151190ten␤»
&testee.unwrap($testee-handler);
say testee(10, "ten");
# OUTPUT: «6.151190ten␤»
```

# [Defining operators](#Functions "go to top of document")[§](#Defining_operators "direct link")

Operators are just subroutines with funny names. The funny names are composed of the category name (`infix`, `prefix`, `postfix`, `circumfix`, `postcircumfix`), followed by a colon, and a list of the operator name or names (two components in the case of circumfix and postcircumfix). An expanded explanation of all these operators and what they mean is included [in this table](/language/operators#Operator_classification).

This works both for adding multi candidates to existing operators and for defining new ones. In the latter case, the definition of the new subroutine automatically installs the new operator into the grammar, but only in the current lexical scope. Importing an operator via `use` or `import` also makes it available.

```raku
# adding a multi candidate to an existing operator:
multi infix:<+>(Int $x, "same") { 2 * $x };
say 21 + "same";            # OUTPUT: «42␤»

# defining a new operator
sub postfix:<!>(Int $x where { $x >= 0 }) { [*] 1..$x };
say 6!;                     # OUTPUT: «720␤»

```

The operator declaration becomes available as soon as possible, so you can recurse into a just-defined operator:

```raku
sub postfix:<!>(Int $x where { $x >= 0 }) {
    $x == 0 ?? 1 !! $x * ($x - 1)!
}
say 6!;                     # OUTPUT: «720␤»

```

Circumfix and postcircumfix operators are made of two delimiters, one opening and one closing.

```raku
sub circumfix:<START END>(*@elems) {
    "start", @elems, "end"
}

say START 'a', 'b', 'c' END;        # OUTPUT: «(start [a b c] end)␤»

```

Postcircumfixes also receive the term after which they are parsed as an argument:

```raku
sub postcircumfix:<!! !!>($left, $inside) {
    "$left -> ( $inside )"
}
say 42!! 1 !!;      # OUTPUT: «42 -> ( 1 )␤»

```

Blocks can be assigned directly to operator names. Use a variable declarator and prefix the operator name with an `&`-sigil.

```raku
my &infix:<ieq> = -> |l { [eq] l>>.fc };
say "abc" ieq "Abc";
# OUTPUT: «True␤»
```

## [Precedence](#Functions "go to top of document")[§](#Precedence "direct link")

Operator precedence in Raku is specified relative to existing operators. The traits `is tighter`, `is equiv` and `is looser` can be provided with an operator to indicate how the precedence of the new operator is related to other, existing ones. More than one trait can be applied.

For example, `infix:<*>` has a tighter precedence than `infix:<+>`, and squeezing one in between works like this:

```raku
sub infix:<!!>($a, $b) is tighter(&infix:<+>) {
    2 * ($a + $b)
}

say 1 + 2 * 3 !! 4;     # OUTPUT: «21␤»

```

Here, the `1 + 2 * 3 !! 4` is parsed as `1 + ((2 * 3) !! 4)`, because the precedence of the new `!!` operator is between that of `+` and `*`.

The same effect could have been achieved with:

```raku
sub infix:<!!>($a, $b) is looser(&infix:<*>) { ... }
```

To put a new operator on the same precedence level as an existing operator, use `is equiv(&other-operator)` instead.

## [Associativity](#Functions "go to top of document")[§](#Associativity "direct link")

When the same operator appears several times in a row, there are multiple possible interpretations. For example:

```raku
1 + 2 + 3
```

could be parsed as

```raku
(1 + 2) + 3         # left associative
```

or as

```raku
1 + (2 + 3)         # right associative
```

For addition of real numbers, the distinction is somewhat moot, because `+` is [mathematically associative](https://en.wikipedia.org/wiki/Associative_property).

But for other operators it matters a great deal. For example, for the exponentiation/power operator, `infix:<**>`:

```raku
say 2 ** (2 ** 3);      # OUTPUT: «256␤»
say (2 ** 2) ** 3;      # OUTPUT: «64␤»
```

Raku has the following possible associativity configurations:

| Associativity | Meaning of $a ! $b ! $c |
| --- | --- |
| left | ($a ! $b) ! $c |
| right | $a ! ($b ! $c) |
| non | ILLEGAL |
| chain | ($a ! $b) and ($b ! $c) |
| list | infix:<!>($a; $b; $c) |

The [Operator docs](/language/operators#Operator_associativity) contain additional details about operator associativity.

You can specify the associativity of an infix operator with the `is assoc` trait, where `left` is the default associativity. Specifying the associativity of non-infix operators is planed but not yet implemented.

```raku
sub infix:<§>(*@a) is assoc<list> {
    '(' ~ @a.join('|') ~ ')';
}

say 1 § 2 § 3;      # OUTPUT: «(1|2|3)␤»

```

# [Traits](#Functions "go to top of document")[§](#Traits "direct link")

*Traits* are subroutines that run at compile time and modify the behavior of a type, variable, routine, attribute, or other language object.

Examples of traits are:

```raku
class ChildClass is ParentClass { ... }
#                ^^ trait, with argument ParentClass
has $.attrib is rw;
#            ^^^^^  trait with name 'rw'
class SomeClass does AnotherRole { ... }
#               ^^^^ trait
has $!another-attribute handles <close>;
#                       ^^^^^^^ trait

```

... and also `is tighter`, `is looser`, `is equiv` and `is assoc` from the previous section.

Traits are subs declared in the form `trait_mod<VERB>`, where `VERB` stands for the name like `is`, `does` or `handles`. It receives the modified thing as argument, and the name as a named argument. See [`Sub`](/type/Sub#Traits) for details.

```raku
multi trait_mod:<is>(Routine $r, :$doubles!) {
    $r.wrap({
        2 * callsame;
    });
}

sub square($x) is doubles {
    $x * $x;
}

say square 3;       # OUTPUT: «18␤»

```

See [type Routine](/type/Routine) for the documentation of built-in routine traits.

# [Re-dispatching](#Functions "go to top of document")[§](#Re-dispatching "direct link")

There are cases in which a routine might want to call the next method from a chain. This chain could be a list of parent classes in a class hierarchy, or it could be less specific multi candidates from a multi dispatch, or it could be the inner routine from a `wrap`.

Fortunately, we have a series of re-dispatching tools that help us to make it easy.

## [The Next Tools](#Functions "go to top of document")[§](#The_Next_Tools "direct link")

The table below represents the next tools in relation to three attributes:

* **Returns:** "Yes" means that it returns, and the code will continue from that point. "No" means that it never returns to this function -- it's as though the call has a built-in "return".
* **Arguments:** Specifically, whether the arguments from the current function are reused in the call, or whether you need to specify some arguments. In the case of `nextcallee`, there are no arguments needed, because they're instead passed to the return value when it's called.
* **Referee:** This is the method that will be called by the tool (the reciprocal of "referrer"). It can be one of:

* **next:** The next item in the chain
* **self:** It will call itself again, as in recursion
* **preset:** It will call the item that was saved by `nextcallee`

|  | Returns | Arguments | Referee\* |
| --- | --- | --- | --- |
| nextsame | No | Reuse | next |
| nextwith | No | Specify | next |
| callsame | Yes | Reuse | next |
| callwith | Yes | Specify | next |
| nextcallee | Yes | None | next |
| samewith | Yes | Specify | self |
| nextcallee's rv\* | Yes | Specify | preset |

\* `nextcallee`'s rv is the tool returned from calling `nextcallee`, which itself can be called.

From the above we learn:

* `with` always means that the arguments need to be specified -- this one is consistent.
* `same` at word end means the arguments of the currently running function will automatically be reused when calling the referee. Note that `samewith`, despite containing "same", doesn't mean that the arguments will be reused. That's because the "same" here refers to the Referee -- the function is calling the same method as itself, not the next in the call stack.
* `next` means that it won't return, except for `nextcallee`, which does return

## [sub callsame](#Functions "go to top of document")[§](#sub_callsame "direct link")

`callsame` calls the next matching candidate with the same arguments that were used for the current candidate and returns that candidate's return value.

```raku
proto a(|) {*}

multi a(Any $x) {
    say "Any $x";
    return 5;
}

multi a(Int $x) {
    say "Int $x";
    my $res = callsame;
    say "Back in Int with $res";
}

a 1;        # OUTPUT: «Int 1␤Any 1␤Back in Int with 5␤»

```

## [sub callwith](#Functions "go to top of document")[§](#sub_callwith "direct link")

`callwith` calls the next candidate matching the original signature, that is, the next function that could possibly be used with the arguments provided by users and returns that candidate's return value.

```raku
proto a(|) {*}

multi a(Any $x) {
    say "Any $x";
    return 5;
}
multi a(Int $x) {
    say "Int $x";
    my $res = callwith($x + 1);
    say "Back in Int with $res";
}

a 1;        # OUTPUT: «Int 1␤Any 2␤Back in Int with 5␤»

```

Here, `a 1` calls the most specific [`Int`](/type/Int) candidate first, and `callwith` re-dispatches to the less specific [`Any`](/type/Any) candidate. Note that although our parameter `$x + 1` is an [`Int`](/type/Int), still we call the next candidate in the chain.

In this case, for example:

```raku
proto how-many(|) {*}

multi how-many( Associative $a ) {
    say "Associative $a ";
    my $calling = callwith( 1 => $a );
    return $calling;
}

multi how-many( Pair $a ) {
    say "Pair $a ";
    return "There is $a "

}

multi how-many( Hash $a ) {
    say "Hash $a";
    return "Hashing $a";
}

my $little-piggy = little => 'piggy';
say $little-piggy.^name;        # OUTPUT: «Pair␤»
say &how-many.cando( \( $little-piggy ));
# OUTPUT: «(sub how-many (Pair $a) { #`(Sub|68970512) ... } sub how-many (Associative $a) { #`(Sub|68970664) ... })␤»
say how-many( $little-piggy  ); # OUTPUT: «Pair little     piggy␤There is little piggy␤»

```

the only candidates that take the [`Pair`](/type/Pair) argument supplied by the user are the two functions defined first. Although a [`Pair`](/type/Pair) can be easily coerced to a [`Hash`](/type/Hash), here is how signatures match:

```raku
say :( Pair ) ~~ :( Associative ); # OUTPUT: «True␤»
say :( Pair ) ~~ :( Hash );        # OUTPUT: «False␤»

```

The arguments provided by us are a [`Pair`](/type/Pair). It does not match a [`Hash`](/type/Hash), so the corresponding function is thus not included in the list of candidates, as can be seen by the output of `&how-many.cando( \( $little-piggy ));`.

## [sub nextsame](#Functions "go to top of document")[§](#sub_nextsame "direct link")

`nextsame` calls the next matching candidate with the same arguments that were used for the current candidate and **never** returns.

```raku
proto a(|) {*}

multi a(Any $x) {
    say "Any $x";
    return 5;
}
multi a(Int $x) {
    say "Int $x";
    nextsame;
    say "never executed because nextsame doesn't return";
}

a 1;        # OUTPUT: «Int 1␤Any 1␤»

```

## [sub nextwith](#Functions "go to top of document")[§](#sub_nextwith "direct link")

`nextwith` calls the next matching candidate with arguments provided by users and **never** returns.

```raku
proto a(|) {*}

multi a(Any $x) {
    say "Any $x";
    return 5;
}
multi a(Int $x) {
    say "Int $x";
    nextwith($x + 1);
    say "never executed because nextwith doesn't return";
}

a 1;        # OUTPUT: «Int 1␤Any 2␤»

```

## [sub samewith](#Functions "go to top of document")[§](#sub_samewith "direct link")

`samewith` calls the multi again with arguments provided at the call site and returns the value provided by the call. This can be used for self-recursion.

```raku
proto factorial(|) {*}

multi factorial(Int $x where * ≤ 1) { 1 }
multi factorial(Int $x) {
    $x * samewith($x-1);
}

say (factorial 10); # OUTPUT: «36288000␤»

```

## [sub nextcallee](#Functions "go to top of document")[§](#sub_nextcallee "direct link")

Redispatch may be required to call a block that is not the current scope what provides `nextwith` and friends with the problem to referring to the wrong scope. Use `nextcallee` to capture the right candidate and call it at the desired time.

```raku
proto pick-winner(|) {*}

multi pick-winner (Int \s) {
    my &nextone = nextcallee;
    Promise.in(π²).then: { nextone s }
}
multi pick-winner { say "Woot! $^w won" }

with pick-winner ^5 .pick -> \result {
    say "And the winner is...";
    await result;
}

# OUTPUT:
# And the winner is...
# Woot! 3 won

```

The [`Int`](/type/Int) candidate takes the `nextcallee` and then fires up a [`Promise`](/type/Promise) to be executed in parallel, after some timeout, and then returns. We can't use `nextsame` here, because it'd be trying to `nextsame` the Promise's block instead of our original routine.

Note that, despite its name, the `nextcallee` function is like:

* `callwith`/`nextwith`, in that it takes parameters
* `callwith`/`callsame`, in that it returns; the call to `nextcallee` returns a reference, and the call to the reference also returns (unlike `nextwith`/`nextsame`, which don't return)

## [Wrapped routines](#Functions "go to top of document")[§](#Wrapped_routines "direct link")

Besides those already mentioned above, re-dispatch is helpful in many more situations. For instance, for dispatching to wrapped routines:

```raku
# enable wrapping:
use soft;

# function to be wrapped:
sub square-root($x) { $x.sqrt }

&square-root.wrap(sub ($num) {
   nextsame if $num >= 0;
   1i * callwith(abs($num));
});

say square-root(4);     # OUTPUT: «2␤»
say square-root(-4);    # OUTPUT: «0+2i␤»

```

## [Routines of parent class](#Functions "go to top of document")[§](#Routines_of_parent_class "direct link")

Another use case is to re-dispatch to methods from parent classes.

```raku
say Version.new('1.0.2') # OUTPUT: v1.0.2

```

```raku
class LoggedVersion is Version {
    method new(|c) {
        note "New version object created with arguments " ~ c.raku;
        nextsame;
    }
}

say LoggedVersion.new('1.0.2');

# OUTPUT:
# New version object created with arguments \("1.0.2")
# v1.0.2

```

# [Coercion types](#Functions "go to top of document")[§](#Coercion_types "direct link")

Coercion types force a specific type for routine arguments while allowing the routine itself to accept a wider input. When invoked, the arguments are narrowed automatically to the stricter type, and therefore within the routine the arguments have always the desired type.

In the case the arguments cannot be converted to the stricter type, a *Type Check* error is thrown.

```raku
sub double(Int(Cool) $x) {
    2 * $x
}

say double '21';# OUTPUT: «42␤»
say double  21; # OUTPUT: «42␤»
say double Any; # Type check failed in binding $x; expected 'Cool' but got 'Any'

```

In the above example, the [`Int`](/type/Int) is the target type to which the argument `$x` will be coerced, and [`Cool`](/type/Cool) is the type that the routine accepts as wider input.

If the accepted wider input type is [`Any`](/type/Any), it is possible to abbreviate the coercion `Int(Any)` by omitting the [`Any`](/type/Any) type, thus resulting in `Int()`.

The coercion works by looking for a method with the same name as the target type: if such method is found on the argument, it is invoked to convert the latter to the expected narrow type. From the above, it is clear that it is possible to provide coercion among user types just providing the required methods:

```raku
class Bar {
   has $.msg;
}

class Foo {
   has $.msg = "I'm a foo!";

   # allows coercion from Foo to Bar
   method Bar {
       Bar.new(:msg($.msg ~ ' But I am now Bar.'));
   }
}

# wants a Bar, but accepts Any
sub print-bar(Bar() $bar) {
   say $bar.^name; # OUTPUT: «Bar␤»
   say $bar.msg;   # OUTPUT: «I'm a foo! But I am now Bar.␤»
}

print-bar Foo.new;

```

In the above code, once a `Foo` instance is passed as argument to `print-bar`, the `Foo.Bar` method is called and the result is placed into `$bar`.

Coercion types are supposed to work wherever types work, but Rakudo currently (2018.05) only implements them in signatures, for both parameters and return types.

Coercion also works with return types:

```raku
sub are-equal (Int $x, Int $y --> Bool(Int) ) { $x - $y };

for (2,4) X (1,2) -> ($a,$b) {
    say "Are $a and $b equal? ", are-equal($a, $b);
} #  OUTPUT: «Are 2 and 1 equal? True␤Are 2 and 2 equal? False␤Are 4 and 1 equal? True␤Are 4 and 2 equal? True␤»

```

In this case, we are coercing an [`Int`](/type/Int) to a [`Bool`](/type/Bool), which is then printed (put into a string context) in the `for` loop that calls the function.

# [sub MAIN](#Functions "go to top of document")[§](#sub_MAIN "direct link")

Declaring a `sub MAIN` is not compulsory in Raku scripts, but you can provide one to create a [command line interface](/language/create-cli) for your script.