andthen
ErrorsCollection

andthen

Synthesised documentation from language/operators

From language/operators

See Original text in context

The andthen operator returns Empty upon encountering the first undefined argument, otherwise the last argument. Last argument is returned as-is, without being checked for definedness at all. Short-circuits. The result of the left side is bound to $_ for the right side, or passed as arguments if the right side is a Callable, whose .count must be 0 or 1.

A handy use of this operator is to alias a routine's return value to $_ and to do additional manipulation with it, such as printing or returning it to caller. Since the andthen operator short-circuits, statements on the right-hand side won't get executed, unless left-hand side is defined (tip: Failures are never defined, so you can handle them with this operator).

sub load-data {
    rand  > .5 or return# simulated load data failure; return Nil 
    (rand > .3 ?? 'error' !! 'good data'xx 10 # our loaded data 
}
load-data.first: /good/ andthen say "$_ is good";
# OUTPUT: «(good data is good)␤» 
 
load-data() andthen .return# return loaded data, if it's defined 
die "Failed to load data!!";

The above example will print good data is good only if the subroutine returned any items that match /good/ and will die unless loading data returned a defined value. The aliasing behavior lets us pipe the values across the operator.

The andthen operator is a close relative of with statement modifier, and some compilers compile with to andthen, meaning these two lines have equivalent behavior:

.say with 42;
42 andthen .say;