Operators

Common Raku infixes, prefixes, postfixes, and more!

See creating operators on how to define new operators.

Operator precedence

The precedence and associativity of Raku operators determine the order of evaluation of operands in expressions.

Where two operators with a different precedence act on the same operand, the subexpression involving the higher-precedence operator is evaluated first. For instance, in the expression 1 + 2 * 3, both the binary + operator for addition and the binary * operator for multiplication act on the operand 2. Because the * operator has a higher precedence than the + operator, the subexpression 2 * 3 will be evaluated first. Consequently, the resulting value of the overall expression is 7 and not 9.

Instead of "precedence" one can also speak of "binding": operators with a higher precedence are then said to have a tighter binding to the operand(s) in question, while operators with a lower precedence are said to have a looser binding. In practice one may also encounter blends of terminology, such as statements that an operator has a tighter or looser precedence.

The following table summarizes the precedence levels offered by Raku, listing them in order from high to low precedence. For each precedence level the table also indicates the associativity (discussed more below) of the operators assigned to that level and lists some example operators at that precedence level.

Precedence Level Associativity Examples
Term¹ non 42 3.14 "eek" qq["foo"] $x :!verbose @$array rand time now ∅
Method call left .meth .\+ .? .* .() .[] .{} .<>» .:: .= .^ .: i
Autoincrement non \+\+ --
Exponentiation right **
Symbolic unary left ! \+ - ~ ? \| \|\| \+^ ~^ ?^ ^ //
Dotty infix¹ left .= .
Multiplicative left * × / ÷ % %% \+& \+< \+> ~& ~< ~> ?& div mod gcd lcm
Additive left \+ - − \+\| \+^ ~\| ~^ ?\| ?^
Replication left x xx
Concatenation list ~ o ∘
Junctive and list & (&) (.) ∩ ⊍
Junctive or list \| ^ (\|) (^) (\+) (-) ∪ ⊖ ⊎ ∖
Named unary¹ left temp let
Structural non but does <=> leg unicmp cmp coll .. ..^ ^.. ^..^
Chaining chain != ≠ == ⩵ < <= ≤ > >= ≥ eq ne lt le gt ge ~~ === ⩶ eqv !eqv =~= ≅ (elem) (cont) (<) (>) (<=) (>=) (<\+) (>\+) (==) ∈ ∊ ∉ ∋ ∍ ∌ ≡ ≢ ⊂ ⊄ ⊃ ⊅ ⊆ ⊈ ⊇ ⊉ ≼ ≽
Tight and list &&
Tight or list \|\| ^^ // min max
Conditional¹ right ?? !! ff ff^ ^ff ^ff^ fff fff^ ^fff ^fff^
Item assignment right =² => \+= -= **= xx=
Loose unary left so not
Comma list , :
List infix list Z minmax X X~ X* Xeqv ... … ...^ …^ ^... ^… ^...^ ^…^
List prefix right =³ ??? !!! ... [\+] [*] Z=
Loose and list and andthen notandthen
Loose or list or xor orelse
Sequencer¹ list <== ==> <<== ==>>
Terminator¹ non ; {...} unless extra ) ] }

Notes:

  • for the precedence levels marked with ¹, there are no operator subroutines with that precedence level (usually because the operators at that precedence level are special-cased by the compiler). This means that you cannot access that precedence level when setting the precedence of custom operators.

  • denotes item assignment while denotes list assignment operator.

Operator associativity

Where two operators with a same precedence level act on an operand, the associativity of the operators determines which subexpression/operator is evaluated first. For instance, in the expression 100 / 2 * 10, the binary division operator / and the binary multiplication operator * have equal precedence, so that the order of their evaluation is determined by their associativity. As the two operators are left associative, operations are grouped from the left like this: (100 / 2) * 10. The expression thus evaluates to 500. Conversely, if / and * had both been right associative, the expression would have been grouped as 100 / (2 * 10) and would have evaluated to 5.

The following table shows how each associativity affects the interpretation of an expression involving three such operators of equal precedence and the same associativity (using a fictitious infix § operator):

Associativity Meaning of $a § $b § $c § $d
left (($a § $b) § $c) § $d
right $a § ($b § ($c § $d))
non ILLEGAL
chain ($a § $b) and ($b § $c) and ($c § $d)
list infix:<§>($a, $b, $c, $d)

Although this table only depicts infix operators, associativity also determines the order of evaluation for expressions with other types of operators. For example, if you created an infix § operator with the precedence equiv(&prefix:<~>), then the order of evaluation of ~$a § $b would depend on what associativity you assigned to §. If § is left associative, then ~$a will be evaluated first and then passed to §; if § is right associative, then $a § $b will be evaluated first and passed to ~.

When two operators have the same precedence but different associativity, determining the grouping of operands is more complicated. However, for operators built in to Raku, all operators with the same precedence level also have the same associativity.

Setting the associativity of non-infix operators is not yet implemented.

In the operator descriptions below, a default associativity of left is assumed.

Operator classification

Operators can occur in several positions relative to a term:

\+term prefix
term1 \+ term2 infix
term\+\+ postfix
(term) circumfix
term1[term2] postcircumfix
.+(term) method

Each operator (except method operators) is also available as a subroutine. The name of the routine is formed from the operator category, followed by a colon, then a list quote construct with the symbol(s) that make up the operator:

infix:<+>(1, 2);                # same as 1 + 2
    circumfix:«[ ]»(<a b c>);       # same as [<a b c>]

As a special case, a listop (list operator) can stand either as a term or as a prefix. Subroutine calls are the most common listops. Other cases include metareduced infix operators ([+] 1, 2, 3) and the listop ... etc. stub operators.

Defining custom operators is covered in Defining operators functions.

Substitution operators

Each substitution operator comes into two main forms: a lowercase one (e.g., s///) that performs in-place (i.e., destructive behavior; and an uppercase form (e.g., S///) that provides a non-destructive behavior.

s/// in-place substitution

my $str = 'old string';
    $str ~~ s/o .+ d/new/;
    say $str; # OUTPUT: «new string␤»

s/// operates on the $_ topical variable, changing it in place. It uses the given Regex to find portions to replace and changes them to the provided replacement string. Sets $/ to the Match object or, if multiple matches were made, a List of Match objects. Returns $/.

It's common to use this operator with the ~~ smartmatch operator, as it aliases left-hand side to $_, which s/// uses.

Regex captures can be referenced in the replacement part; it takes the same adverbs as the .subst method, which go between the s and the opening /, separated with optional whitespace:

my $str = 'foo muCKed into the lEn';
# replace second 'o' with 'x'
    $str ~~ s:2nd/o/x/;
# replace 'M' or 'L' followed by non-whitespace stuff with 'd'
    # and lower-cased version of that stuff:
    $str ~~ s :g :i/<[ML]> (\S+)/d{lc $0}/;
say $str; # OUTPUT: «fox ducked into the den␤»

You can also use a different delimiter:

my $str = 'foober';
    $str ~~ s!foo!fox!;
    $str ~~ s{b(.)r} = " d$0n";
    say $str; # OUTPUT: «fox den␤»

Non-paired characters can simply replace the original slashes. Paired characters, like curly braces, are used only on the match portion, with the substitution given by assignment (of anything: a string, a routine call, etc.).

S/// non-destructive substitution

say S/o .+ d/new/ with 'old string';      # OUTPUT: «new string␤»
    S:g/« (.)/$0.uc()/.say for <foo bar ber>; # OUTPUT: «Foo␤Bar␤Ber␤»

S/// uses the same semantics as the s/// operator, except it leaves the original string intact and returns the resultant string instead of $/ ($/ still being set to the same values as with s///).

Note: since the result is obtained as a return value, using this operator with the ~~ smartmatch operator is a mistake and will issue a warning. To execute the substitution on a variable that isn't the $_ this operator uses, alias it to $_ with given, with, or any other way. Alternatively, use the .subst method.

tr/// in-place transliteration

my $str = 'old string';
    $str ~~ tr/dol/wne/;
    say $str; # OUTPUT: «new string␤»

tr/// operates on the $_ topical variable and changes it in place. It behaves similar to Str.trans called with a single Pair argument, where key is the matching part (characters dol in the example above) and value is the replacement part (characters wne in the example above). Accepts the same adverbs as Str.trans. Returns the StrDistance object that measures the distance between original value and the resultant string.

my $str = 'old string';
    $str ~~ tr:c:d/dol st//;
    say $str; # OUTPUT: «old st␤»

TR/// non-destructive transliteration

with 'old string' {
        say TR/dol/wne/; # OUTPUT: «new string␤»
    }

TR/// behaves the same as the tr/// operator, except that it leaves the $_ value untouched and instead returns the resultant string.

say TR:d/dol // with 'old string'; # OUTPUT: «string␤»

Assignment operators

Raku has a variety of assignment operators, which can be roughly classified as simple assignment operators and compound assignment operators.

The simple assignment operator symbol is =. It is 'overloaded' in the sense that it can mean either item assignment or list assignment depending on the context in which it is used:

my $x = 1;        # item assignment; $x = 1
    my @x = 1,2,3;    # list assignment; @x = [1,2,3]

See the section on item and list assignment for a more elaborate and comparative discussion of these two types of assignment.

The compound assignment operators are metaoperators: they combine the simple assignment operator = with an infix operator to form a new operator that performs the operation specified by the infix operator before assigning the result to the left operand. Some examples of built-in compound assignment operators are +=, -=, *=, /=, min=, and ~=. Here is how they work:

my $a = 32;
    $a += 10;         # $a = 42
    $a -= 2;          # $a = 40
$a = 3;
    $a min= 5;        # $a = 3
    $a min= 2;        # $a = 2
my $s = 'a';
    $s ~= 'b';        # $s = 'ab'
# And an example of a custom operator:
    sub infix:<space-concat> ($a, $b) { $a ~ " " ~ $b };
    $a = 'word1';
    $a space-concat= 'word2';                 # OUTPUT: «'word1 word2'␤»

One thing the simple and compound assignment operators have in common is that they form so-called assignment expressions that return or evaluate to the assigned value:

my sub fac (Int $n) { [*] 1..$n };        # sub for calculating factorial
    my @x = ( my $y = fac(100), $y*101 );     # @x = [100!, 101!]
my $i = 0;
    repeat { say $i } while ($i += 1) < 10;   # OUTPUT: «0,1,2,...9␤»

In the first example, the assignment expression my $y = fac(100) declares $y, assigns the value fac(100) to it, and finally returns the assigned value fac(100). The returned value is then taken into account for constructing the List. In the second example the compound-assignment expression $i += 1 assigns the value $i + 1 to $i, and subsequently evaluates to the assigned value $i+1, thus allowing the returned value to be used for judging the while loop condition.

In dealing with simple and compound assignment operators, it is tempting to think that for instance the following two statements are (always) equivalent:

expression1 += expression2;                     # compound assignment
expression1  = expression1 + expression2;       # simple assignment

They are not, however, for two reasons. Firstly, expression1 in the compound assignment statement is evaluated only once, whereas expression1 in the simple assignment statement is evaluated twice. Secondly, the compound assignment statement may, depending on the infix operator in question, implicitly initialize expression1 if it is a variable with an undefined value. Such initialization will not occur for expression1 in the simple assignment statement.

The aforementioned two differences between the simple and compound assignment statements are briefly elucidated below.

The first difference is common amongst programming languages and mostly self-explanatory. In the compound assignment, there is only one expression1 that is explicitly specified to serve both as a term of the addition to be performed and as the location where the result of the addition, the sum, is to be stored. There is thus no need to evaluate it twice. The simple assignment, in contrast, is more generic in the sense that the value of the expression1 that serves as a term of the addition need not necessarily be the same as the value of the expression1 that defines the location where the sum must be stored. The two expressions are therefore evaluated separately. The distinction is particularly relevant in cases where the evaluation of expression1 has side effects in the form of changes to one or more variables:

my @arr = [10, 20, 30]; my $i = 0;

if rand < 1/2 { @arr[++$i] += 1; # @arr = [10,21,30] } else { @arr[++$i] = @arr[++$i] + 1; # @arr = [10,31,30] (or [10,20,21]?) } # the result may be implementation-specific say @arr;

The second difference pointed out above is related to the widespread practice of using compound assignment operators in accumulator patterns. Such patterns involve a so-called accumulator: a variable that calculates the sum or a product of a series of values in a loop. To obviate the need for explicit accumulator initialization, Raku's compound assignment operators silently take care of the initialization where this is sensibly possible:

my @str = "Cleanliness is next to godliness".comb; my ($len, $str); for @str -> $c { $len += 1; $str ~= $c; } say "The string '$str' has $len characters.";

In this example the accumulators $len and $str are implicitly initialized to 0 and "", respectively, which illustrates that the initialization value is operator-specific. In this regard it is also noted that not all compound assignment operators can sensibly initialize an undefined left-hand side variable. The /= operator, for instance, will not arbitrarily select a value for the dividend; instead, it will throw an exception.

Although not strictly operators, methods can be used in the same fashion as compound assignment operators:

my $a = 3.14; $a .= round; # $a = $a.round; OUTPUT: «3»

Metaoperators

Metaoperators can be parameterized with other operators or subroutines in the same way as functions can take other functions as parameters. To use a subroutine as a parameter, prefix its name with an &. Raku will generate the actual combined operator in the background, allowing the mechanism to be applied to user defined operators. To disambiguate chained metaoperators, enclose the inner operator in square brackets. There are quite a few metaoperators with different semantics as explained, next.

Negated relational operators

The result of a relational operator returning Bool can be negated by prefixing with !. To avoid visual confusion with the !! operator, you may not modify any operator already beginning with !.

There are shortcuts for !== and !eq, namely != and ne.

my $a = True;
    say so $a != True;    # OUTPUT: «False␤»
    my $i = 10;
my $release = Date.new(:2015year, :12month, :24day);
    my $today = Date.today;
    say so $release !before $today;     # OUTPUT: «False␤»

Reversed operators

Any infix operator may be called with its two arguments reversed by prefixing with R. Associativity of operands is reversed as well.

say 4 R/ 12;               # OUTPUT: «3␤»
    say [R/] 2, 4, 16;         # OUTPUT: «2␤»
    say [RZ~] <1 2 3>,<4 5 6>  # OUTPUT: «(41 52 63)␤»

<<Hyper operators>;Operators,«;Operators,»;Operators,»=«;Operators,«=»>>>

Hyper operators include « and », with their ASCII variants << and >>. They apply a given operator enclosed (or preceded or followed, in the case of unary operators) by « and/or » to one or two lists, returning the resulting list, with the pointy part of « or » aimed at the shorter list. Single elements are turned to a list, so they can be used too. If one of the lists is shorter than the other, the operator will cycle over the shorter list until all elements of the longer list are processed.

say (1, 2, 3) »*» 2;          # OUTPUT: «(2 4 6)␤»
    say (1, 2, 3, 4) »~» <a b>;   # OUTPUT: «(1a 2b 3a 4b)␤»
    say (1, 2, 3) »+« (4, 5, 6);  # OUTPUT: «(5 7 9)␤»
    say (&sin, &cos, &sqrt)».(0.5);
    # OUTPUT: «(0.479425538604203 0.877582561890373 0.707106781186548)␤»

The last example illustrates how postcircumfix operators (in this case .()) can also be hypered.

my @a = <1 2 3>;
    my @b = <4 5 6>;
    say (@a,@b)»[1]; # OUTPUT: «(2 5)␤»

In this case, it's the postcircumfix[] which is being hypered.

Assignment metaoperators can be hyped.

my @a = 1, 2, 3;
    say @a »+=» 1;    # OUTPUT: «[2 3 4]␤»
    my ($a, $b, $c);
    (($a, $b), $c) «=» ((1, 2), 3);
    say "$a, $c";       #  OUTPUT: «1, 3␤»

Hyper forms of unary operators have the pointy bit aimed at the operator and the blunt end at the list to be operated on.

my @wisdom = True, False, True;
    say !« @wisdom;     # OUTPUT: «[False True False]␤»
my @a = 1, 2, 3;
    @a»++;
    say @a;             # OUTPUT: «[2 3 4]␤»

Hyper operators are defined recursively on nested arrays.

say -« [[1, 2], 3]; # OUTPUT: «[[-1 -2] -3]␤»

Also, methods can be called in an out of order, concurrent fashion. The resulting list will be in order. Note that all hyper operators are candidates for parallelism and will cause tears if the methods have side effects. The optimizer has full reign over hyper operators, which is the reason that they cannot be defined by the user.

class CarefulClass { method take-care {} }
    my CarefulClass @objs;
    my @results = @objs».take-care();
my @slops;        # May Contain Nuts
    @slops».?this-method-may-not-exist();

Hyper operators can work with hashes. The pointy direction indicates if missing keys are to be ignored in the resulting hash. The enclosed operator operates on all values that have keys in both hashes.

%foo «+» %bar; intersection of keys
%foo »+« %bar; union of keys
%outer »+» %inner; only keys of %inner that exist in %outer will occur in the result
my %outer = 1, 2, 3 Z=> <a b c>;
    my %inner = 1, 2 Z=> <x z>;
    say %outer «~» %inner;          # OUTPUT: «{"1" => "ax", "2" => "bz"}␤»

Hyper operators can take user-defined operators as their operator argument.

sub pretty-file-size (Int $size --> Str) {
        # rounding version of infix:</>(Int, Int)
        sub infix:<r/>(Int \i1, Int \i2) {
            round(i1 / i2, 0.1)
        }
# we build a vector of fractions of $size and zip that with the fitting prefix
        for $size «[r/]« (2**60, 2**50, 2**40, 2**30, 2**20, 2**10)
                  Z      <EB     PB     TB     GB     MB     KB> -> [\v,\suffix] {
            # starting with the biggest suffix,
            # we take the first that is 0.5 of that suffix or bigger
            return v ~ ' ' ~ suffix if v > 0.4
        }
        # this be smaller or equal then 0.4 KB
        return $size.Str;
    }
for 60, 50, 40, 30, 20, 10 -> $test {
        my &a = { (2 ** $test) * (1/4, 1/2, 1, 10, 100).pick * (1..10).pick };
        print pretty-file-size(a.Int) xx 2, ' ';
    }
# OUTPUT: «10 EB 4 EB 2 PB 5 PB 0.5 PB 4 TB 300 GB 4.5 GB 50 MB 200 MB 9 KB 0.6 MB␤»

Whether hyperoperators descend into child lists depends on the nodality of the inner operator of a chain. For the hyper method call operator (».), the nodality of the target method is significant.

say (<a b>, <c d e>)».elems;        # OUTPUT: «(2 3)␤»
    say (<a b>, <c d e>)».&{ .elems };  # OUTPUT: «((1 1) (1 1 1))␤»

You can chain hyper operators to destructure a List of Lists.

my $neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0));
    my $p = (2, 3);
    say $neighbors »>>+<<» ($p, *);   # OUTPUT: «((1 3) (2 2) (2 4) (3 3))␤»

Reduction metaoperators

The reduction metaoperator, [ ], reduces a list with the given infix operator. It gives the same result as the reduce routine - see there for details.

# These two are equivalent:
    say [+] 1, 2, 3;                # OUTPUT: «6␤»
    say reduce &infix:<+>, 1, 2, 3; # OUTPUT: «6␤»

No whitespace is allowed between the square brackets and the operator. To wrap a function instead of an operator, provide an additional layer of square brackets:

sub plus { $^a + $^b };
    say [[&plus]] 1, 2, 3;          # OUTPUT: «6␤»

The argument list is iterated without flattening. This means that you can pass a nested list to the reducing form of a list infix operator:

say [X~] (1, 2), <a b>;         # OUTPUT: «(1a 1b 2a 2b)␤»

which is equivalent to 1, 2 X~ <a b>.

By default, only the final result of the reduction is returned. Prefix the wrapped operator with a \, to return a lazy list of all intermediate values instead. This is called a "triangular reduce". If the non-meta part contains a \ already, quote it with [] (e.g. [\[\x]]).

my @n = [\~] 1..*;
    say @n[^5];         # OUTPUT: «(1 12 123 1234 12345)␤»

Cross metaoperators

The cross metaoperator, X, will apply a given infix operator in order of cross product to all lists, such that the rightmost operand varies most quickly.

1..3 X~ <a b> # OUTPUT: «<1a, 1b, 2a, 2b, 3a, 3b>␤»

Zip metaoperator

The zip metaoperator (which is not the same thing as Z) will apply a given infix operator to pairs taken one left, one right, from its arguments. The resulting list is returned.

my @l = <a b c> Z~ 1, 2, 3;     # OUTPUT: «[a1 b2 c3]␤»

If one of the operands runs out of elements prematurely, the zip operator will stop. An infinite list can be used to repeat elements. A list with a final element of * will repeat its 2nd last element indefinitely.

my @l = <a b c d> Z~ ':' xx *;  # OUTPUT: «<a: b: c: d:>»
       @l = <a b c d> Z~ 1, 2, *;   # OUTPUT: «<a1 b2 c2 d2>»

If an infix operator is not given, the , (comma operator) will be used by default:

my @l = 1 Z 2;  # OUTPUT: «[(1 2)]»

Sequential operators

The sequential metaoperator, S, will suppress any concurrency or reordering done by the optimizer. Most simple infix operators are supported.

say so 1 S& 2 S& 3;  # OUTPUT: «True␤»

Nesting of metaoperators

To avoid ambiguity when chaining metaoperators, use square brackets to help the compiler understand you.

my @a = 1, 2, 3;
    my @b = 5, 6, 7;
    @a X[+=] @b;
    say @a;         # OUTPUT: «[19 20 21]␤»

Term precedence

term < >

The quote-words construct breaks up the contents on whitespace and returns a List of the words. If a word looks like a number literal or a Pair literal, it's converted to the appropriate number.

say <a b c>[1];   # OUTPUT: «b␤»

term ( )

The grouping operator.

An empty group () creates an empty list. Parentheses around non-empty expressions simply structure the expression, but do not have additional semantics.

In an argument list, putting parenthesis around an argument prevents it from being interpreted as a named argument.

multi p(:$a!) { say 'named'      }
    multi p($a)   { say 'positional' }
    p a => 1;           # OUTPUT: «named␤»
    p (a => 1);         # OUTPUT: «positional␤»

term { }

Block or Hash constructor.

If the content is empty, or contains a single list that starts with a Pair literal or %-sigiled variable, and the $_ variable or placeholder parameters are not used, the constructor returns a Hash. Otherwise it constructs a Block.

To force construction of a Block, follow the opening brace with a semicolon. To always ensure you end up with a Hash, you can use %( ) coercer or hash routine instead:

{}.^name.say;        # OUTPUT: «Hash␤»
    {;}.^name.say;       # OUTPUT: «Block␤»
{:$_}.^name.say;     # OUTPUT: «Block␤»
    %(:$_).^name.say;    # OUTPUT: «Hash␤»
    hash(:$_).^name.say; # OUTPUT: «Hash␤»

circumfix [ ]

The Array constructor returns an itemized Array that does not flatten in list context. Check this:

say .raku for [3,2,[1,0]]; # OUTPUT: «3␤2␤$[1, 0]␤»

This array is itemized, in the sense that every element constitutes an item, as shown by the $ preceding the last element of the array, the (list) item contextualizer.

Terms

Terms have their own extended documentation.

Method postfix precedence

postcircumfix [ ]

sub postcircumfix:<[ ]>(@container, **@index,
                            :$k, :$v, :$kv, :$p, :$exists, :$delete)

Universal interface for positional access to zero or more elements of @container, a.k.a. "array indexing operator".

my @alphabet = 'a' .. 'z';
    say @alphabet[0];                   # OUTPUT: «a␤»
    say @alphabet[1];                   # OUTPUT: «b␤»
    say @alphabet[*-1];                 # OUTPUT: «z␤»
    say @alphabet[100]:exists;          # OUTPUT: «False␤»
    say @alphabet[17, 0, 10, 20].join;  # OUTPUT: «raku␤»
    say @alphabet[23 .. *].raku;        # OUTPUT: «("x", "y", "z")␤»
@alphabet[1, 2] = "B", "C";
    say @alphabet[0..3].raku;           # OUTPUT: «("a", "B", "C", "d")␤»

See Subscripts, for a more detailed explanation of this operator's behavior and for how to implement support for it in custom types.

postcircumfix { }

sub postcircumfix:<{ }>(%container, **@key,
                            :$k, :$v, :$kv, :$p, :$exists, :$delete)

Universal interface for associative access to zero or more elements of a %container, a.k.a. "hash indexing operator".

my %color = kiwi => "green", banana => "yellow", cherry => "red";
    say %color{"banana"};                 # OUTPUT: «yellow␤»
    say %color{"cherry", "kiwi"}.raku;    # OUTPUT: «("red", "green")␤»
    say %color{"strawberry"}:exists;      # OUTPUT: «False␤»
%color{"banana", "lime"} = "yellowish", "green";
    %color{"cherry"}:delete; # note that value is always returned but removal only happens when delete is true.
    say %color;             # OUTPUT: «banana => yellowish, kiwi => green, lime => green␤»

See postcircumfix < >|/language/operators#postcircumfix_<_> and postcircumfix « »|/routine/« »#(Operators)_postcircumfix_«_» for convenient shortcuts, and Subscripts for a more detailed explanation of this operator's behavior and how to implement support for it in custom types.

postcircumfix <>

Decontainerization operator, which extracts the value from a container and makes it independent of the container type.

use JSON::Tiny;

my $config = from-json('{ "files": 3, "path": "/home/some-user/raku.rakudoc" }');
say $config.raku;      # OUTPUT: «${:files(3), :path("/home/some-user/raku.rakudoc")}␤»
my %config-hash = $config<>;
say %config-hash.raku; # OUTPUT: «{:files(3), :path("/home/some-user/raku.rakudoc")}␤»

It's a Hash in both cases, and it can be used like that; however, in the first case it was in item context, and in the second case it has been extracted to its proper context.

postcircumfix < >

Shortcut for postcircumfix { } that quotes its argument using the same rules as the quote-words operator|#term_<_> of the same name.

my %color = kiwi => "green", banana => "yellow", cherry => "red";
    say %color<banana>;               # OUTPUT: «yellow␤»
    say %color<cherry kiwi>.raku;     # OUTPUT: «("red", "green")␤»
    say %color<strawberry>:exists;    # OUTPUT: «False␤»

Technically, not a real operator; it's syntactic sugar that's turned into the { } postcircumfix operator at compile-time.

postcircumfix « »

Shortcut for postcircumfix { } that quotes its argument using the same rules as the interpolating quote-words operator|/language/quoting#Word_quoting_with_interpolation_and_quote_protection:_«_» of the same name.

my %color = kiwi => "green", banana => "yellow", cherry => "red";
    my $fruit = "kiwi";
    say %color«cherry "$fruit"».raku;   # OUTPUT: «("red", "green")␤»

Technically, not a real operator; it's syntactic sugar that's turned into the { } postcircumfix operator at compile-time.

postcircumfix ( )

The call operator treats the invocant as a Callable and invokes it, using the expression between the parentheses as arguments.

Note that an identifier followed by a pair of parentheses is always parsed as a subroutine call.

If you want your objects to respond to the call operator, implement a method CALL-ME.

methodop .

The operator for calling one method, $invocant.method.

Technically, not a real operator; it's syntax special-cased in the compiler.

|Syntax,methodop .&

methodop .&

The operator to call a Callable, such as a Block, a Method, or a Sub with method syntax. The invocant will be bound to the first positional argument (and thus dispatch will fail if the Callable does not accept at least one positional argument).

Technically, not a real operator; it's syntax special-cased in the compiler.

my sub f($invocant){ "The arg has a value of $invocant" }
    42.&f;
    # OUTPUT: «The arg has a value of 42␤»
42.&(-> $invocant { "The arg has a value of $invocant" });
    # OUTPUT: «The arg has a value of 42␤»

methodop .=

A mutating method call. $invocant.=method desugars to $invocant = $invocant.method, similar to = (item assignment) .

Technically, not a real operator; it's syntax special-cased in the compiler.

|Syntax,methodop .^

methodop .^

A metamethod call. $invocant.^method calls method on $invocant's metaclass. It desugars to $invocant.HOW.method($invocant, ...). See the metaobject protocol documentation for more information.

Technically, not a real operator; it's syntax special-cased in the compiler. It can be also applied, within classes, to access metamethods on self:

class Foo {
    has $.a = 3;
    method bar {
        return $.^name
    }
};
say Foo.new.bar; # OUTPUT: «Foo␤»

|Syntax,methodop .?

methodop .?

Safe call operator. $invocant.?method calls method method on $invocant if it has a method of such name. Otherwise it returns Nil.

Technically, not a real operator; it's syntax special-cased in the compiler.

|Syntax,methodop .+

methodop .+

$foo.+meth walks the MRO and calls all the methods called meth and submethods called meth if the type is the same as type of $foo. Those methods might be multis, in which case the matching candidate would be called.

After that, a List of the results are returned. If no such method was found, it throws an X::Method::NotFound exception.

class A {
      method foo { say "from A"; }
    }
    class B is A {
      multi method foo { say "from B"; }
      multi method foo(Str) { say "from B (Str)"; }
    }
    class C is B is A {
      multi method foo { say "from C"; }
      multi method foo(Str) { say "from C (Str)"; }
    }
say C.+foo; # OUTPUT: «from C␤from B␤from A␤(True True True)␤»

|Syntax,methodop .*

methodop .*

$foo.*meth walks the MRO and calls all the methods called meth and submethods called meth if the type is the same as type of $foo. Those methods might be multis, in which case the matching candidate would be called.

After that, a List of the results are returned. If no such method was found, an empty List is returned.

Technically, postfix .+ calls .* at first. Read postfix .+ section to see examples.

.>|Syntax,methodop >>.

methodop ». / methodop >>.

This is the hyper method call operator. Will call a method on all elements of a List out of order and return the list of return values in order.

my @a = <a b c>;
my @b = @a».ord;                  # OUTPUT: «[97, 98, 99]␤»
# The first parameter of a method is the invocant.
sub foo(Str:D $c){ $c.ord * 2 };
# So we can pretend to have a method call with a sub that got a good
# first positional argument.
say @a».&foo;
# Blocks have an implicit positional arguments that lands in $_. The latter can
# be omitted for method calls.
say @a».&{ .ord};

Hyper method calls may appear to be the same as doing a map call, however along with being a hint to the compiler that it can parallelize the call, the behavior is also affected by nodality of the method being invoked, depending on which either nodemap or deepmap semantics are used to perform the call.

The nodality is checked by looking up whether the Callable provides nodal method. If the hyper is applied to a method, that Callable is that method name, looked up on List type; if the hyper is applied to a routine (e.g. ».&foo), that routine functions as that Callable. If the Callable is determined to provide nodal method, nodemap semantics are used to perform the hyper call, otherwise duckmap semantics are used.

Take care to avoid a common mistake|/language/traps#Using_»_and_map_interchangeably of expecting side-effects to occur in order. The following say is not guaranteed to produce the output in order:

@a».say;  # WRONG! Could produce a␤b␤c␤ or c␤b␤a␤ or any other order

methodop .postfix / .postcircumfix

In most cases, a dot may be placed before a postfix or postcircumfix:

my @a;
    @a[1, 2, 3];
    @a.[1, 2, 3]; # Same

This can be useful for visual clarity or brevity. For example, if an object's attribute is a function, putting a pair of parentheses after the attribute name will become part of the method call. So, either two pairs of parentheses must be used or a dot has to come before the parentheses to separate it from the method call.

class Operation {
        has $.symbol;
        has &.function;
    }
    my $addition = Operation.new(:symbol<+>, :function{ $^a + $^b });
    say $addition.function()(1, 2);   # OUTPUT: «3␤»
    # OR
    say $addition.function.(1, 2);    # OUTPUT: «3␤»

If the postfix is an identifier, however, it will be interpreted as a normal method call.

1.i # No such method 'i' for invocant of type 'Int'

Technically, not a real operator; it's syntax special-cased in the compiler.

methodop .:<prefix operator>

An operator in prefix form can still be called like a method, that is, using the . methodop notation, by preceding it by a colon. For example:

my $a = 1;
    say ++$a;       # OUTPUT: «2␤»
    say $a.:<++>;   # OUTPUT: «3␤»

Technically, not a real operator; it's syntax special-cased in the compiler, that is why it's classified as a methodop.

methodop .::

A class-qualified method call, used to call a method as defined in a parent class or role, even after it has been redefined in the child class.

class Bar {
        method baz { 42 }
    }
    class Foo is Bar {
        method baz { "nope" }
    }
    say Foo.Bar::baz;       # OUTPUT: «42␤»

postfix ,=

Creates an object that concatenates, in a class-dependent way, the contents of the variable on the left hand side and the expression on the right hand side:

my %a = :11a, :22b;
    %a ,= :33x;
    say %a # OUTPUT: «{a => 11, b => 22, x => 33}␤»

Autoincrement precedence

prefix C«++|Prefix operators,prefix ++>

multi prefix:<++>($x is rw) is assoc<non>

Increments its argument by one and returns the updated value.

my $x = 3;
    say ++$x;   # OUTPUT: «4␤»
    say $x;     # OUTPUT: «4␤»

It works by calling the succ method (for successor) on its argument, which gives custom types the freedom to implement their own increment semantics.

prefix C«--|Prefix operators,prefix -->

multi prefix:<-->($x is rw) is assoc<non>

Decrements its argument by one and returns the updated value.

my $x = 3;
    say --$x;   # OUTPUT: «2␤»
    say $x;     # OUTPUT: «2␤»

It works by calling the pred method (for predecessor) on its argument, which gives custom types the freedom to implement their own decrement semantics.

postfix C«++|Postfix operators,postfix ++>

multi postfix:<++>($x is rw) is assoc<non>

Increments its argument by one and returns the original value.

my $x = 3;
    say $x++;   # OUTPUT: «3␤»
    say $x;     # OUTPUT: «4␤»

It works by calling the succ method (for successor) on its argument, which gives custom types the freedom to implement their own increment semantics; when undefined, it sets the value to 1 and returns it.

my $x;
    $x++;
    say $x;     # OUTPUT: «1␤»

Note that this does not necessarily return its argument; e.g., for undefined values, it returns 0:

my $x;
    say $x++;   # OUTPUT: «0␤»
    say $x;     # OUTPUT: «1␤»

Increment on Str will increment the number part of a string and assign the resulting string to the container. An is rw container is required.

my $filename = "somefile-001.txt";
    say $filename++ for 1..3;
    # OUTPUT: «somefile-001.txt␤somefile-002.txt␤somefile-003.txt␤»

This will act on any Unicode numeral:

my $was٧ = "ثمانية٧";
$was٧++;
say $was٧; # OUTPUT: «ثمانية٨␤»

Including, since version 6.d, Thai numerals

my $เลขไทย="๙๙";
$เลขไทย++;
say $เลขไทย; # OUTPUT: «๑๐๐␤»

postfix C«--|Postfix operators,postfix -->

multi postfix:<-->($x is rw) is assoc<non>

Decrements its argument by one and returns the original value.

my $x = 3;
    say $x--;   # OUTPUT: «3␤»
    say $x;     # OUTPUT: «2␤»

It works by calling the pred method (for predecessor) on its argument, which gives custom types the freedom to implement their own decrement semantics.

Note that this does not necessarily return its argument;e.g., for undefined values, it returns 0:

my $x;
    say $x--;   # OUTPUT: «0␤»
    say $x;     # OUTPUT: «-1␤»

Decrement on Str will decrement the number part of a string and assign the resulting string to the container. An is rw container is required. Crossing 0 is prohibited and throws X::AdHoc.

my $filename = "somefile-003.txt";
    say $filename-- for 1..3;
    # OUTPUT: «somefile-003.txt␤somefile-002.txt␤somefile-001.txt␤»

Exponentiation precedence

infix **

multi infix:<**>(Any, Any --> Numeric:D) is assoc<right>

The exponentiation operator coerces both arguments to Numeric and calculates the left-hand-side raised to the power of the right-hand side.

If the right-hand side is a non-negative integer and the left-hand side is an arbitrary precision type (Int, FatRat), then the calculation is carried out without loss of precision.

Unicode superscripts will behave in exactly the same way.

sub squared( Int $num ) { $num² };
    say squared($_) for ^5; # OUTPUT: «0␤1␤4␤9␤16␤»

It also works for sequences of several Unicode superscript numbers:

sub twenty-second-power( Int $num ) { $num²² };
    say twenty-second-power($_) for ^5; # OUTPUT: «0␤1␤4194304␤31381059609␤17592186044416␤»

Symbolic unary precedence

prefix ?

multi prefix:<?>(Mu --> Bool:D)

Boolean context operator.

Coerces the argument to Bool by calling the Bool method on it. Note that this collapses Junctions.

prefix !

multi prefix:<!>(Mu --> Bool:D)

Negated Boolean context operator.

Coerces the argument to Bool by calling the Bool method on it, and returns the negation of the result. Note that this collapses Junctions.

prefix //

multi prefix:<//>(Any --> Bool:D)

Boolean context operator.

Available as of 6.e language version (early implementation exists in Rakudo compiler 2022.12+).

Coerces the argument to Boolean by calling the defined method on it.

prefix +

multi prefix:<+>(Any --> Numeric:D)

Numeric context operator.

Coerces the argument to Numeric by calling the Numeric method on it.

prefix -

multi prefix:<->(Any --> Numeric:D)

Negative numeric context operator.

Coerces the argument to Numeric by calling the Numeric method on it, and then negates the result.

prefix ~

multi prefix:<~>(Any --> Str:D)

String context operator.

Coerces the argument to Str by calling the Str method on it.

prefix |

Flattens objects of type Capture, Pair, List, Map and Hash into an argument list.

sub slurpee( |args ){
        say args.raku
    };
    slurpee( <a b c d>, { e => 3 }, 'e' => 'f' => 33 )
    # OUTPUT: «\(("a", "b", "c", "d"), {:e(3)}, :e(:f(33)))␤»

Please see the signature literals page, specially the section on Captures for more information on the subject.

Outside of argument lists, it returns a Slip, which makes it flatten into the outer list. Inside argument list Positionals are turned into positional arguments and Associatives are turned into named arguments.

prefix +^

multi prefix:<+^>(Any --> Int:D)

Integer bitwise negation operator: converts the number to binary using as many bytes as needed by the number plus one; flips all bits and returns the result assuming it is a two's complement representation.

say +^255; # OUTPUT: «-256␤»

In this case, 255 is 11111111 and would need a single byte. We use the representation in bytes needed for this value plus one, converting it to 0000 0000 1111 1111. Bitwise negation turns it into 1111 1111 0000 0000 and this is the representation in two's complement of -256, which is returned.

say +^1;        # OUTPUT: «-2␤»
say +^(-256);   # OUTPUT: «255␤»

Negative numbers are assumed to be represented as two's complements, and thus circle back to the original number.

prefix ~^

Coerces the argument to a non-variable-encoding string buffer type (e.g. buf8, buf16, buf32) and then flips each bit in that buffer.

Please note that this has not yet been implemented.

prefix ?^

multi prefix:<?^>(Mu --> Bool:D)

Boolean bitwise negation operator: Coerces the argument to Bool and then does a bit flip, which makes it the same as prefix:<!>.

prefix ^

multi prefix:<^>(Any --> Range:D)

upto operator.

Coerces the argument to Numeric, and generates a range from 0 up to (but excluding) the argument.

say ^5;         # OUTPUT: «0..^5␤»
    for ^5 { }      # 5 iterations

Dotty infix precedence

These operators are like their Method Postfix counterparts, but require surrounding whitespace (before and/or after) to distinguish them.

infix .=

Calls the right-side method on the value in the left-side container, replacing the resulting value in the left-side container.

In most cases, this behaves identically to the postfix mutator, but the precedence is lower:

my $a = -5;
say ++$a.=abs;
# OUTPUT: «6␤»
say ++$a .= abs;
# OUTPUT: «Cannot modify an immutable Int␤
#           in block <unit> at <tmp> line 1␤␤»

infix .

Calls the following method (whose name must be alphabetic) on the left-side invocant.

Note that the infix form of the operator has a slightly lower precedence than postfix .meth.

say -5.abs;      # like: -(5.abs)
    # OUTPUT: «-5␤»
    say -5 . abs;    # like: (-5) . abs
    # OUTPUT: «5␤»
    say -5 .abs;     # following whitespace is optional
    # OUTPUT: «5␤»

Multiplicative precedence

infix *

multi infix:<*>(Any, Any --> Numeric:D)

Multiplication operator.

Coerces both arguments to Numeric and multiplies them. The result is of the wider type. See Numeric for details.

infix /

multi infix:</>(Any, Any --> Numeric:D)

Division operator.

Coerces both argument to Numeric and divides the left through the right number. Division of Int values returns Rat, otherwise the "wider type" rule described in Numeric holds.

Note there is also div for Int division.

infix div

multi infix:<div>(Int:D, Int:D --> Int:D)

Integer division operator. Rounds down.

Note there is also / for Numeric division.

infix %

multi infix:<%>($x, $y --> Numeric:D)

Modulo operator. Coerces to Numeric first.

Generally the following identity holds:

my ($x, $y) = 1,2;
    $x % $y == $x - floor($x / $y) * $y

Note there is also mod for Int modulo.

infix %%

multi infix:<%%>($a, $b --> Bool:D)

Divisibility operator. Returns True if $a % $b == 0.

infix mod

multi infix:<mod>(Int:D $a, Int:D $b --> Int:D)

Integer modulo operator. Returns the remainder of an integer modulo operation.

Note there is also % for Numeric modulo.

infix +&

multi infix:<+&>($a, $b --> Int:D)

Numeric bitwise AND operator. Coerces both arguments to Int and does a bitwise AND operation assuming two's complement.

infix +<

multi infix:«+<»($a, $b --> Int:D)

Integer bit shift to the left.

infix +>

multi infix:«+>»($a, $b --> Int:D)

Integer bit shift to the right.

infix ~&

Coerces each argument to a non-variable-encoding string buffer type (e.g. buf8, buf16, buf32) and then performs a numeric bitwise AND on corresponding integers of the two buffers, padding the shorter buffer with zeroes.

infix ~<

Coerces the left argument to a non-variable-encoding string buffer type (e.g. buf8, buf16, buf32) and then performs a numeric bitwise left shift on the bits of the buffer.

Please note that this has not yet been implemented.

infix ~>

Coerces the left argument to a non-variable-encoding string buffer type (e.g. buf8, buf16, buf32) and then performs a numeric bitwise right shift on the bits of the buffer.

Please note that this has not yet been implemented.

infix ?&

multi infix:<?&>(Mu $x = Bool::True)
    multi infix:<?&>(Mu \a, Mu \b)

Boolean logical AND operator. Coerces the argument(s) to Bool and performs logical AND on it(them): it will return True if and only if both arguments are True. On a single argument it behaves as identity, returning the coerced value.

infix gcd

multi infix:<gcd>($a, $b --> Int:D)

Coerces both arguments to Int and returns the greatest common divisor. If one of its arguments is 0, the other is returned (when both arguments are 0, the operator returns 0).

infix lcm

multi infix:<lcm>($a, $b --> Int:D)

Coerces both arguments to Int and returns the least common multiple; that is, the smallest integer that is evenly divisible by both arguments.

Additive precedence

infix +

multi infix:<+>($a, $b --> Numeric:D)

Addition operator: Coerces both arguments to Numeric and adds them. From version 6.d it works also on Duration, DateTime and Real types.

infix -

multi infix:<->($a, $b --> Numeric:D)

Subtraction operator: Coerces both arguments to Numeric and subtracts the second from the first. From version 6.d it works also on Duration, DateTime and Real types.

infix +|

multi infix:<+|>($a, $b --> Int:D)

Integer bitwise OR operator: Coerces both arguments to Int and does a bitwise OR (inclusive OR) operation.

infix +^

multi infix:<+^>($a, $b --> Int:D)

Integer bitwise XOR operator: Coerces both arguments to Int and does a bitwise XOR (exclusive OR) operation.

say (0b00001101 +^ 0b00001001).base(2); # OUTPUT: «100␤»

infix ~|

Coerces each argument to a non-variable-encoding string buffer type (e.g. buf8, buf16, buf32) and then performs a numeric bitwise OR on corresponding integers of the two buffers, padding the shorter buffer with zeroes.

infix ~^

Coerces each argument to a non-variable-encoding string buffer type (e.g. buf8, buf16, buf32) and then performs a numeric bitwise XOR on corresponding integers of the two buffers, padding the shorter buffer with zeroes.

infix ?^

multi infix:<?^>(Mu $x = Bool::False)
    multi infix:<?^>(Mu \a, Mu \b)

Boolean logical XOR operator. Coerces the argument(s) to Bool and performs logical XOR on it(them): it will return True if and only if just one of the argument is True. On a single argument it behaves as identity, returning the coerced value.

infix ?|

multi infix:<?|>(Mu $x = Bool::False)
    multi infix:<?|>(Mu \a, Mu \b)

Boolean logical OR operator. Coerces the argument(s) to Bool and performs logical OR (inclusive OR) on it(them): it will return True if at least one of the argument is True. On a single argument it behaves as identity, returning the coerced value.

Replication precedence

infix x

sub infix:<x>($a, $b --> Str:D)

String repetition operator.

Repeats the string $a $b times, if necessary coercing $a to Str and $b to Int. Returns an empty string if $b <= 0. An exception X::Numeric::CannotConvert will be thrown if $b is -Inf or NaN.

say 'ab' x 3;           # OUTPUT: «ababab␤»
    say 42 x 3;             # OUTPUT: «424242␤»
my $a = 'a'.IO;
    my $b = 3.5;
    say $a x $b;            # OUTPUT: «aaa␤»

infix xx

multi infix:<xx>()
    multi infix:<xx>(Mu \x)
    multi infix:<xx>(&x, Num:D() $n)
    multi infix:<xx>(&x, Whatever)
    multi infix:<xx>(&x, Bool:D $b)
    multi infix:<xx>(&x, Int:D $n)
    multi infix:<xx>(Mu \x, Num:D() $n)
    multi infix:<xx>(Mu \x, Whatever)
    multi infix:<xx>(Mu \x, Bool:D $b)
    multi infix:<xx>(Mu \x, Int:D $n)

List repetition operator

In general, it returns a Sequence of $a repeated and evaluated $b times ($b is coerced to Int). If $b <= 0, the empty list is returned. It will return an error with no operand, and return the operand itself with a single operand. An exception X::Numeric::CannotConvert will be thrown if $b is -Inf or NaN.

The left-hand side is evaluated for each repetition, so

say [1, 2] xx 5;
    # OUTPUT: «([1 2] [1 2] [1 2] [1 2] [1 2])␤»

returns five distinct arrays (but with the same content each time), and

rand xx 3

returns three pseudo random numbers that are determined independently.

The right-hand side can be *, in which case a lazy, infinite list is returned. If it's a Bool, a Seq with a single element is returned if it's True.

Concatenation

Same as the rest of the infix operators, these can be combined with metaoperators such as assignment, for instance.

infix ~

multi infix:<~>(Any,   Any)
    multi infix:<~>(Str:D, Str:D)
    multi infix:<~>(Buf:D, Buf:D)
    multi infix:<~>(Blob:D $a, Blob:D $b)
    multi infix:<~>(Junction:D \a, Junction:D \b)

This is the string concatenation operator, which coerces both arguments to Str and concatenates them. If both arguments are Buf, a combined buffer is returned.

say 'ab' ~ 'c';     # OUTPUT: «abc␤»
my $bob = Blob.new([1,2,3]);
my $bao = Blob.new([3,4,5]);
say $bao ~ $bob;     # OUTPUT: «Blob:0x<03 04 05 01 02 03>␤»

The arity-1 version of this operator will be called when the hyper version of the operator is used on an array or list with a single element, or simply an element

say [~] Blob.new([3,4,5]);     # OUTPUT: «Blob:0x<03 04 05>␤»
say [~] 1|2;                   # OUTPUT: «any(1, 2)␤»

infix o, infix

multi infix:<o>()
    multi infix:<o>(&f)
    multi infix:<o>(&f, &g --> Block:D)

The function composition operator infix:<∘> or infix:<o> combines two functions, so that the left function is called with the return value of the right function. If the .count of the left function is greater than 1, the return value of the right function will be slipped into the left function.

Both .count and .arity of the right-hand side will be maintained, as well as the .of of the left hand side.

sub f($p){ say 'f'; $p / 2 }
sub g($p){ say 'g'; $p * 2 }

my &composed = &f ∘ &g;
say composed 2; # OUTPUT: «g␤f␤2␤»
# equivalent to:
say 2.&g.&f;
# or to:
say f g 2;
say &composed.arity; #  OUTPUT: «1␤»
say &composed.count; #  OUTPUT: «1␤»
say &composed.of;    #  OUTPUT: «(Mu)␤»
sub f($a, $b, $c) { [~] $c, $b, $a }
sub g($str){ $str.comb }
my &composed = &f ∘ &g;
say composed 'abc'; # OUTPUT: «cba␤»
# equivalent to:
say f |g 'abc';

The single-arg candidate returns the given argument as is. The zero-arg candidate returns an identity routine that simply returns its argument.

my &composed = [∘] &uc;
    say composed 'foo'; # OUTPUT: «FOO␤»
my &composed = [∘];
    say composed 'foo'; # OUTPUT: «foo␤»

Junctive AND (all) precedence

infix &

multi infix:<&>($a, $b --> Junction:D) is assoc<list>

All junction operator.

Creates an all Junction from its arguments. See Junction for more details.

infix (&), infix

multi infix:<(&)>(**@p)

Intersection operator.

'&' as in left hand side arguments 'and' right hand side arguments. Returns the intersection of all of its arguments. This creates a new Set that contains only the elements common to all of the arguments if none of the arguments are a Bag, BagHash, Mix or MixHash.

say <a b c> (&) <b c d>; # OUTPUT: «Set(b c)␤»
say <a b c d> ∩ <b c d e> ∩ <c d e f>; # OUTPUT: «Set(c d)␤»

If any of the arguments are Baggy or Mixy, the result is a new Bag (or Mix) containing the common elements, each weighted by the largest common weight (which is the minimum of the weights of that element over all arguments).

say <a a b c a> (&) bag(<a a b c c>); # OUTPUT: «Bag(a(2) b c)␤»

infix (.), infix

multi infix:<(.)>(**@p)

Baggy multiplication operator.

Returns the Baggy multiplication of its arguments, i.e., a Bag that contains each element of the arguments with the weights of the element across the arguments multiplied together to get the new weight. Returns a Mix if any of the arguments is a Mixy.

say <a b c> (.) <a b c d>; # OUTPUT: «Bag(a b c)␤»
                           # Since 1 * 0 == 0, in the case of 'd'
say <a a b c a d> ⊍ bag(<a a b c c>); # OUTPUT: «Bag(a(6) b c(2))␤»

Junctive OR (any) precedence

infix |

multi infix:<|>($a, $b --> Junction:D) is assoc<list>

Creates an any Junction from its arguments.

my $three-letters = /<[a b c]>/ | /<[i j k]>/ | /<[x y z]>/;
    say $three-letters.raku; # OUTPUT: «any(/<[a b c]>/, /<[i j k]>/, /<[x y z]>/)␤»
    say 'b' ~~ $three-letters; # OUTPUT: «True␤»

This first creates an any Junction of three regular expressions (every one of them matching any of 3 letters), and then uses smartmatching to check whether the letter b matches any of them, resulting in a positive match. See also Junction for more details.

infix (|), infix

multi infix:<(|)>(**@p)

Union operator.

'|' as in left hand side arguments 'or' right hand side arguments.

Returns the union of all of its arguments. This creates a new Set that contains all the elements its arguments contain if none of the arguments are a Bag, BagHash, Mix or MixHash.

say <a b d> ∪ bag(<a a b c>); # OUTPUT: «Bag(a(2) b c d)␤»

If any of the arguments are Baggy or Mixy, the result is a new Bag (or Mix) containing all the elements, each weighted by the highest weight that appeared for that element.

say <a b d> ∪ bag(<a a b c>); # OUTPUT: «Bag(a(2) b c d)␤»

infix (+), infix

multi infix:<(+)>(**@p)

Baggy addition operator.

Returns the Baggy addition of its arguments. This creates a new Bag from each element of the arguments with the weights of the element added together to get the new weight, if none of the arguments are a Mix or MixHash.

say <a a b c a d> (+) <a a b c c>; # OUTPUT: «Bag(a(5) b(2) c(3) d)␤»

If any of the arguments is a Mixy, the result is a new Mix.

say <a b c> (+) (a => 2.5, b => 3.14).Mix; # OUTPUT: «Mix(a(3.5) b(4.14) c)␤»

infix (-), infix

multi infix:<(-)>(**@p)

Set difference operator.

Returns the set difference of all its arguments. This creates a new Set that contains all the elements the first argument has but the rest of the arguments don't, i.e., of all the elements of the first argument, minus the elements from the other arguments. But only if none of the arguments are a Bag, BagHash, Mix or MixHash.

say <a a b c a d> (-) <a a b c c>; # OUTPUT: «Set(d)␤»
say <a b c d e> (-) <a b c> (-) <a b d>; # OUTPUT: «Set(e)␤»

If any of the arguments are Baggy or Mixy, the result is a new Bag (or Mix) containing all the elements remaining after the first argument with its weight subtracted by the weight of that element in each of the other arguments.

say <a a b c a d> (-) bag(<a b c c>); # OUTPUT: «Bag(a(2) d)␤»
say <a a b c a d>  ∖  mix(<a b c c>); # OUTPUT: «Mix(a(2) c(-1) d)␤»

infix ^

multi infix:<^>($a, $b --> Junction:D) is assoc<list>

One junction operator.

Creates a one Junction from its arguments. See Junction for more details.

infix (^), infix

multi infix:<(^)>($a, $b)
    multi infix:<(^)>(**@p)

Symmetric set difference operator.

Returns the symmetric set difference of all its arguments. This creates a new Set made up of all the elements that $a has but $b doesn't and all the elements $b has but $a doesn't if none of the arguments are a Bag, BagHash, Mix or MixHash. Equivalent to ($a ∖ $b) ∪ ($b ∖ $a).

say <a b> (^) <b c>; # OUTPUT: «Set(a c)␤»

If any of the arguments are Baggy or Mixy, the result is a new Bag (or Mix).

say <a b> ⊖ bag(<b c>); # OUTPUT: «Bag(a c)␤»

Named unary precedence

prefix temp

sub prefix:<temp>(Mu $a is rw)

"temporizes" the variable passed as the argument. The variable begins with the same value as it had in the outer scope, but can be assigned new values in this scope. Upon exiting the scope, the variable will be restored to its original value.

my $a = "three";
    say $a; # OUTPUT: «three␤»
    {
        temp $a;
        say $a; # OUTPUT: «three␤»
        $a = "four";
        say $a; # OUTPUT: «four␤»
    }
    say $a; # OUTPUT: «three␤»

You can also assign immediately as part of the call to temp:

temp $a = "five";

Be warned the temp effects get removed once the block is left. If you were to access the value from, say, within a Promise after the temp was undone, you'd get the original value, not the temp one:

my $v = "original";
{
    temp $v = "new one";
    start {
        say "[PROMISE] Value before block is left: `$v`";
        sleep 1;
        say "[PROMISE] Block was left while we slept; value is now `$v`";
    }
    sleep ½;
    say "About to leave the block; value is `$v`";
}
say "Left the block; value is now `$v`";
sleep 2;
# OUTPUT:
# [PROMISE] Value before block is left: `new one`
# About to leave the block; value is `new one`
# Left the block; value is now `original`
# [PROMISE] Block was left while we slept; value is now `original`

prefix let

sub prefix:<let>(Mu $a is rw)

Refers to a variable in an outer scope whose value will be restored if the block exits unsuccessfully, implying that the block returned a defined object.

my $name = "Jane Doe";

{
    let $name = prompt("Say your name ");
    die if !$name;
    CATCH {
        default { say "No name entered" }
    }
    say "We have $name";
}

say "We got $name";

This code provides a default name for $name. If the user exits from the prompt or simply does not provide a valid input for $name; let will restore the default value provided at the top. If user input is valid, it will keep that.

Nonchaining binary precedence

infix does

sub infix:<does>(Mu $obj, Mu $role) is assoc<non>

Mixes $role into $obj at runtime. Requires $obj to be mutable.

Similar to but operator, if $role supplies exactly one attribute, an initializer can be passed in parentheses.

Similar to but operator, the $role can instead be an instantiated object, in which case, the operator will create a role for you automatically. The role will contain a single method named the same as $obj.^name and that returns $obj:

my $o = class { method Str { "original" } }.new;
    put $o;            # OUTPUT: «original␤»
    $o does "modded";
    put $o;            # OUTPUT: «modded␤»

If methods of the same name are present already, the last mixed in role takes precedence.

infix but

multi infix:<but>(Mu $obj1, Mu   $role) is assoc<non>
    multi infix:<but>(Mu $obj1, Mu:D $obj2) is assoc<non>

Creates a copy of $obj with $role mixed in. Since $obj is not modified, but can be used to create immutable values with mixins.

If $role supplies exactly one attribute, an initializer can be passed in parentheses:

role Answerable {
    has $.answer;
}
my $ultimate-question = 'Life, the Universe and Everything' but Answerable(42);
say $ultimate-question;         # OUTPUT: «Life, the Universe and Everything␤»
say $ultimate-question.^name;   # OUTPUT: «Str+{Answerable}␤»
say $ultimate-question.answer;  # OUTPUT: «42␤»

Instead of a role, you can provide an instantiated object. In this case, the operator will create a role for you automatically. The role will contain a single method named the same as $obj.^name and that returns $obj:

my $forty-two = 42 but 'forty two';
say $forty-two+33;    # OUTPUT: «75␤»
say $forty-two.^name; # OUTPUT: «Int+{<anon|1>}␤»
say $forty-two.Str;   # OUTPUT: «forty two␤»

Calling ^name shows that the variable is an Int with an anonymous object mixed in. However, that object is of type Str, so the variable, through the mixin, is endowed with a method with that name, which is what we use in the last sentence.

We can also mixin classes, even created on the fly.

my $s = 12 but class Warbles { method hi { 'hello' } }.new;
say $s.Warbles.hi;    # OUTPUT: «hello␤»
say $s + 42;          # OUTPUT: «54␤»

To access the mixed-in class, as above, we use the class name as is shown in the second sentence. If methods of the same name are present already, the last mixed in role takes precedence. A list of methods can be provided in parentheses separated by comma. In this case conflicts will be reported at runtime.

infix cmp

multi infix:<cmp>(Any,       Any)
    multi infix:<cmp>(Real:D,    Real:D)
    multi infix:<cmp>(Str:D,     Str:D)
    multi infix:<cmp>(Version:D, Version:D)

Generic, "smart" three-way comparator.

Compares strings with string semantics, numbers with number semantics, Pair objects first by key and then by value etc.

if $a eqv $b, then $a cmp $b always returns Order::Same.

say (a => 3) cmp (a => 4);   # OUTPUT: «Less␤»
    say 4        cmp 4.0;        # OUTPUT: «Same␤»
    say 'b'      cmp 'a';        # OUTPUT: «More␤»

Strings are compared codepoint by codepoint; if leading codepoints are the same, the result of comparing the first differing codepoint is returned or the longer string if their lengths differ.

"abcd" cmp "abcde";    # OUTPUT: «Less␤»
    "abcd " cmp "abcde";   # OUTPUT: «Less␤»
    'A' cmp 'Ẳ';           # OUTPUT: «Less␤»

infix coll

multi infix:<coll>(Str:D \a, Str:D \b --> Order:D)
    multi infix:<coll>(Cool:D \a, Cool:D \b --> Order:D)
    multi infix:<coll>(Pair:D \a, Pair:D \b --> Order:D)

coll is a sorting operator that takes pairs of Strs, Cools or Pairs and returns an Order that uses the $*COLLATION order. The default behavior disregards diacritic marks and capitalization, for instance.

say "b" cmp "à";  # OUTPUT: «Less␤»
    say "b" coll "à"; # OUTPUT: «More␤»

In the first case, lexicographic or codepoint order is taken into account. In the second, which uses coll, the diacritic is not considered and sorting happens according to intuitive order.

NOTE: These are not yet implemented in the JVM.

infix unicmp

multi infix:<unicmp>(Str:D \a, Str:D \b --> Order:D)
    multi infix:<unicmp>(Pair:D \a, Pair:D \b --> Order:D)
    multi infix:<coll>(Pair:D \a, Pair:D \b --> Order:D)

Unlike the cmp operator which sorts according to codepoint, unicmp and coll sort according to how most users would expect, that is, disregarding aspects of the particular character like capitalization.

say 'a' unicmp 'Z'; # OUTPUT: «Less␤»
    say 'a' coll 'Z';   # OUTPUT: «Less␤»
    say 'a' cmp 'Z';    # OUTPUT: «More␤»

The main difference between coll and unicmp is that the behavior of the former can be changed by the $*COLLATION dynamic variable.

NOTE: These are not yet implemented in the JVM.

infix leg

multi infix:<leg>(Any,   Any)
    multi infix:<leg>(Str:D, Str:D)

String three-way comparator. Short for less, equal or greater?.

Coerces both arguments to Str and then does a lexicographic comparison.

say 'a' leg 'b';       # OUTPUT: «Less␤»
    say 'a' leg 'a';       # OUTPUT: «Same␤»
    say 'b' leg 'a';       # OUTPUT: «More␤»

infix <=>

multi infix:«<=>»($a, $b --> Order:D) is assoc<non>

Numeric three-way comparator.

Coerces both arguments to Real and then does a numeric comparison.

infix ..

multi infix:<..>($a, $b --> Range:D) is assoc<non>

Range operator

Constructs a Range from the arguments.

infix ..^

multi infix:<..^>($a, $b --> Range:D) is assoc<non>

Right-open range operator.

Constructs a Range from the arguments, excluding the end point.

infix ^..

multi infix:<^..>($a, $b --> Range:D) is assoc<non>

Left-open range operator.

Constructs a Range from the arguments, excluding the start point.

infix ^..^

multi infix:<^..^>($a, $b --> Range:D) is assoc<non>

Open range operator.

Constructs a Range from the arguments, excluding both start and end point.

Chaining binary precedence

infix ==, infix

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 (if necessary); returns True if they are equal.

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

infix !=, infix

sub infix:<!=>(Mu, Mu --> Bool:D)

Numeric inequality operator.

Coerces both arguments to Numeric (if necessary); returns True if they are distinct.

Is equivalent to !==.

infix <

multi infix:«<»(Int:D, Int:D)
    multi infix:«<»(Num:D, Num:D)
    multi infix:«<»(Real:D, Real:D)

Numeric less than operator.

Coerces both arguments to Real (if necessary); returns True if the first argument is smaller than the second.

infix <=, infix

multi infix:«<=»(Int:D, Int:D)
    multi infix:«<=»(Num:D, Num:D)
    multi infix:«<=»(Real:D, Real:D)

Numeric less than or equal to operator.

Coerces both arguments to Real (if necessary); returns True if the first argument is smaller than or equal to the second.

infix >

multi infix:«>»(Int:D, Int:D)
    multi infix:«>»(Num:D, Num:D)
    multi infix:«>»(Real:D, Real:D)

Numeric greater than operator.

Coerces both arguments to Real (if necessary); returns True if the first argument is larger than the second.

infix >=, infix

multi infix:«>=»(Int:D, Int:D)
    multi infix:«>=»(Num:D, Num:D)
    multi infix:«>=»(Real:D, Real:D)

Numeric greater than or equal to operator.

Coerces both arguments to Real (if necessary); returns True if the first argument is larger than or equal to the second.

infix eq

multi infix:<eq>(Any,   Any)
    multi infix:<eq>(Str:D, Str:D)

String equality operator.

Coerces both arguments to Str (if necessary); returns True if both are equal.

Mnemonic: equal

infix ne

multi infix:<ne>(Mu,    Mu)
    multi infix:<ne>(Str:D, Str:D)

String inequality operator.

Coerces both arguments to Str (if necessary); returns False if both are equal.

Mnemonic: not equal

infix gt

multi infix:<gt>(Mu,    Mu)
    multi infix:<gt>(Str:D, Str:D)

String greater than operator.

Coerces both arguments to Str (if necessary); returns True if the first is larger than the second, as determined by lexicographic comparison.

Mnemonic: greater than

infix ge

multi infix:<ge>(Mu,    Mu)
    multi infix:<ge>(Str:D, Str:D)

String greater than or equal to operator.

Coerces both arguments to Str (if necessary); returns True if the first is equal to or larger than the second, as determined by lexicographic comparison.

Mnemonic: greater or equal

infix lt

multi infix:<lt>(Mu,    Mu)
    multi infix:<lt>(Str:D, Str:D)

String less than operator.

Coerces both arguments to Str (if necessary); returns True if the first is smaller than the second, as determined by lexicographic comparison.

Mnemonic: less than

infix le

multi infix:<le>(Mu,    Mu)
    multi infix:<le>(Str:D, Str:D)

String less than or equal to operator.

Coerces both arguments to Str (if necessary); returns True if the first is equal to or smaller than the second, as determined by lexicographic comparison.

Mnemonic: less or equal

infix before

multi infix:<before>(Any,       Any)
    multi infix:<before>(Real:D,    Real:D)
    multi infix:<before>(Str:D,     Str:D)
    multi infix:<before>(Version:D, Version:D)

Generic ordering, uses the same semantics as cmp. Returns True if the first argument is smaller than the second.

infix after

multi infix:<after>(Any,       Any)
    multi infix:<after>(Real:D,    Real:D)
    multi infix:<after>(Str:D,     Str:D)
    multi infix:<after>(Version:D, Version:D)

Generic ordering, uses the same semantics as cmp. Returns True if the first argument is larger than the second.

infix eqv

sub infix:<eqv>(Any, Any)

This could be called an equivalence operator, and it will return True if the two arguments are structurally the same, i.e. from the same type and (recursively) contain equivalent values.

say [1, 2, 3] eqv [1, 2, 3];    # OUTPUT: «True␤»
    say Any eqv Any;                # OUTPUT: «True␤»
    say 1 eqv 2;                    # OUTPUT: «False␤»
    say 1 eqv 1.0;                  # OUTPUT: «False␤»

Lazy Iterables cannot be compared, as they're assumed to be infinite. However, the operator will do its best and return False if the two lazy Iterables are of different types or if only one Iterable is lazy.

say (1…∞) eqv (1…∞).List; # Both lazy, but different types;   OUTPUT: «False␤»
    say (1…∞) eqv (1…3);      # Same types, but only one is lazy; OUTPUT: «False␤»
    (try say (1…∞) eqv (1…∞)) # Both lazy and of the same type. Cannot compare; throws.
        orelse say $!.^name;  # OUTPUT: «X::Cannot::Lazy␤»

In some cases, it will be able to compare lazy operands, as long as they can be iterated

my $a = lazy ^2;
my $b = $a;
$a.cache;
say $a eqv $b; # OUTPUT: «True␤»

When cached, the two lazy Seqs can be iterated over, and thus compared.

The default eqv operator even works with arbitrary objects. E.g., eqv will consider two instances of the same object as being structurally equivalent:

my class A {
        has $.a;
    }
    say A.new(a => 5) eqv A.new(a => 5);  # OUTPUT: «True␤»

Although the above example works as intended, the eqv code might fall back to a slower code path in order to do its job. One way to avoid this is to implement an appropriate infix eqv operator:

my class A {
        has $.a;
    }
    multi infix:<eqv>(A $l, A $r) { $l.a eqv $r.a }
    say A.new(a => 5) eqv A.new(a => 5);            # OUTPUT: «True␤»

Note that eqv does not work recursively on every kind of container type, e.g. Set:

my class A {
        has $.a;
    }
    say Set(A.new(a => 5)) eqv Set(A.new(a => 5));  # OUTPUT: «False␤»

Even though the contents of the two sets are eqv, the sets are not. The reason is that eqv delegates the equality check to the Set object which relies on element-wise === comparison. Turning the class A into a value type (ValueObjAt) by giving it a WHICH method produces the expected behavior:

my class A {
        has $.a;
        method WHICH {
            ValueObjAt.new: "A|$!a.WHICH()"
        }
    }
    say Set(A.new(a => 5)) eqv Set(A.new(a => 5));  # OUTPUT: «True␤»

You can call a single-argument version of the operator by using its full name; it will always return true.

say infix:<eqv>(33);    # OUTPUT: «True␤»
say infix:<eqv>(False); # OUTPUT: «True␤»

infix ===

sub infix:<===>(Any, Any)

The ASCII equivalent of , the value identity operator.

Before Rakudo version 2021.07, the ASCII variant was the only variant.

infix

sub infix:<⩶>(Any, Any)

Value identity operator. Returns True if both arguments are the same object, disregarding any containerization.

my class A { };
    my $a = A.new;
    say $a ⩶ $a;              # OUTPUT: «True␤»
    say A.new ⩶ A.new;        # OUTPUT: «False␤»
    say A ⩶ A;                # OUTPUT: «True␤»

For value types, behaves like eqv:

say 'a' ⩶ 'a';            # OUTPUT: «True␤»
    say 'a' ⩶ 'b';            # OUTPUT: «False␤»
my $b = 'a';
    say $b ⩶ 'a';             # OUTPUT: «True␤»
# different types
    say 1 ⩶ 1.0;              # OUTPUT: «False␤»

uses the WHICH method to obtain the object identity.

If you want to create a class that should act as a value type, then that class must create an instance method WHICH, that should return a ValueObjAt object that won't change for the lifetime of the object.

The ASCII equivalent of this operator is ===.

infix =:=

multi infix:<=:=>(Mu \a, Mu \b)

Container identity operator. Returns True if both arguments are bound to the same container. If it returns True, it generally means that modifying one will also modify the other.

my ($a, $b) = (1, 3);
    say $a =:= $b;      # OUTPUT: «False␤»
    $b = 2;
    say $a;             # OUTPUT: «1␤»
    $b := $a;
    say $a =:= $b;      # OUTPUT: «True␤»
    $a = 5;
    say $b;             # OUTPUT: «5␤»

The single argument version, called as a routine, will always return True:

say infix:<=:=>(42);    # OUTPUT: «True␤»
say infix:<=:=>(False); # OUTPUT: «True␤»

infix ~~

The smartmatch operator aliases the left-hand side to $_, then evaluates the right-hand side and calls .ACCEPTS($_) on it. The semantics are left to the type of the right-hand side operand.

Here is a partial list of some of the built-in smartmatching functionality. For full details, see ACCEPTS documentation for the type on the right-hand side of the operator.

Right-hand side Comparison semantics
Mu:U type check
Str string equality
Numeric numeric equality
Regex regex match
Callable Boolean result of invocation
Set/Bag equal element values
Any:D object identity

infix =~=

The ASCII equivalent of , the approximately-equal operator.

infix

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)

The approximately-equal operator |Infix operators,≅ calculates the relative percentage difference between the left-hand and right-hand sides and returns True if the difference is less than $*TOLERANCE (which defaults to 1e-15). However, if either side is zero then it checks that the absolute difference between the sides is less than $*TOLERANCE.

The ASCII equivalent of this operator is =~=.

Note that this operator is not arithmetically symmetrical (doesn't do ± Δ):

my $x = 1;
    say ($x + $*TOLERANCE) ≅ $x;   # OUTPUT: «False␤»
    say ($x - $*TOLERANCE) ≅ $x;   # OUTPUT: «True␤»

You can change $*TOLERANCE lexically:

{
        my $*TOLERANCE = .1;
        say 11 ≅ 10;        # OUTPUT: «True␤»
    }

Note that setting $*TOLERANCE = 0 will cause all comparisons to fail.

{
        my $*TOLERANCE = 0;
        say 1 ≅ 1;        # OUTPUT: «False␤»
    }

infix (elem), infix ∈

multi infix:<(elem)>($a,$b --> Bool:D)

Membership operator.

Returns True if $a is an element of $b.

say 2 (elem) (1, 2, 3); # OUTPUT: «True␤»
say 4 ∈ (1, 2, 3);      # OUTPUT: «False␤»

Since release 2020.05, ∊ is an alias for this operator.

infix

multi infix:<∉>($a,$b --> Bool:D)

Non-membership operator.

Returns True if $a is not an element of $b. Equivalent to !(elem).

say 4 ∉ (1, 2, 3);       # OUTPUT: «True␤»
say 2 !(elem) (1, 2, 3); # OUTPUT: «False␤»

infix (==), infix

multi infix:<(==)>($a,$b --> Bool:D)

Set equality operator.

Returns True if $a and $b are identical.

say (1, 2, 3) (==) (1, 3, 2); # OUTPUT: «True␤»
say (1, 2, 3) ≡ (1, 2, 4); # OUTPUT: «False␤»

infix

multi infix:<≢>($a,$b --> Bool:D)

Set inequality operator.

Returns True if $a and $b are not identical. Equivalent to !(==).

say (1, 2, 3) ≢ (1, 2, 4); # OUTPUT: «True␤»
say (1, 2, 3) ≢ (1, 3, 2); # OUTPUT: «False␤»

infix (cont), infix ∋

multi infix:<(cont)>($a,$b --> Bool:D)

Membership operator.

Returns True if $a contains $b as an element.

say (1,2,3) (cont) 2; # OUTPUT: «True␤»
say (1, 2, 3) ∋ 4;    # OUTPUT: «False␤»

Since release 2020.05, ∍ is an alias for this operator.

infix

multi infix:<∌>($a,$b --> Bool:D)

Non-membership operator.

Returns True if $a does not contain $b. Equivalent to !(cont).

say (1,2,3) ∌ 4;       # OUTPUT: «True␤»
say (1,2,3) !(cont) 2; # OUTPUT: «False␤»

infix (<), infix

multi infix:«(<)»($a,$b --> Bool:D)

Subset of operator.

Returns True if $a is a strict subset of $b, i.e., that all the elements of $a are elements of $b but $a is a smaller set than $b.

say (1,2,3) (<) (2,3,1); # OUTPUT: «False␤»
say (2,3) (<) (2,3,1);   # OUTPUT: «True␤»
say 4 ⊂ (1,2,3);         # OUTPUT: «False␤»

infix

multi infix:<⊄>($a,$b --> Bool:D)

Not a subset of operator.

Returns True if $a is not a strict subset of $b. Equivalent to !(<).

say (1,2,3) ⊄ (2,3,1); # OUTPUT: «True␤»
say (2,3) ⊄ (2,3,1);   # OUTPUT: «False␤»
say 4 !(<) (1,2,3);    # OUTPUT: «True␤»

infix (<=), infix

multi infix:«(<=)»($a,$b --> Bool:D)

Subset of or equal to operator.

Returns True if $a is a subset of $b, i.e., that all the elements of $a are elements of $b but $a is a smaller or equal sized set than $b.

say (1,2,3) (<=) (2,3,1); # OUTPUT: «True␤»
say (2,3) (<=) (2,3,1);   # OUTPUT: «True␤»
say 4 ⊆ (1,2,3);          # OUTPUT: «False␤»

infix

multi infix:<⊈>($a,$b --> Bool:D)

Not a subset of nor equal to operator.

Returns True if $a is not a subset of $b. Equivalent to !(<=).

say (1,2,3) ⊈ (2,3,1); # OUTPUT: «False␤»
say (2,3) ⊈ (2,3,1);   # OUTPUT: «False␤»
say 4 !(<=) (1,2,3);   # OUTPUT: «True␤»

infix (>), infix

multi infix:«(>)»($a,$b --> Bool:D)

Superset of operator.

Returns True if $a is a strict superset of $b, i.e., that all the elements of $b are elements of $a but $a is a larger set than $b.

say (1,2,3) (>) (2,3,1); # OUTPUT: «False␤»
say (1,2,3) (>) (2,3);   # OUTPUT: «True␤»
say 4 ⊃ (1,2,3);         # OUTPUT: «False␤»

infix

multi infix:<⊅>($a,$b --> Bool:D)

Not a superset of operator.

Returns True if $a is not a strict superset of $b. Equivalent to !(>).

say (1,2,3) ⊅ (2,3,1); # OUTPUT: «True␤»
say (1,2,3) ⊅ (2,3);   # OUTPUT: «False␤»
say 4 !(>) (1,2,3);    # OUTPUT: «True␤»

infix (>=), infix

multi infix:«(>=)»($a,$b --> Bool:D)

Superset of or equal to operator.

Returns True if $a is a superset of $b, i.e., that all the elements of $b are elements of $a but $a is a larger or equal sized set than $b.

say (1,2,3) (>=) (2,3,1); # OUTPUT: «True␤»
say (1,2,3) (>=) (2,3);   # OUTPUT: «True␤»
say 4 ⊇ (1,2,3);          # OUTPUT: «False␤»

infix

multi infix:<⊉>($a,$b --> Bool:D)

Not a superset of nor equal to operator.

Returns True if $a is not a superset of $b. Equivalent to !(>=).

say (1,2,3) ⊉ (2,3,1); # OUTPUT: «False␤»
say (1,2,3) ⊉ (2,3);   # OUTPUT: «False␤»
say 4 !(>=) (1,2,3);   # OUTPUT: «True␤»

Tight AND precedence

infix &&

Returns the first argument that evaluates to False in Boolean context, otherwise returns the last argument.

Note that this short-circuits, i.e. if one of the arguments evaluates to a false value, the arguments to the right are never evaluated.

sub a { 1 }
    sub b { 0 }
    sub c { die "never called" };
    say a() && b() && c();      # OUTPUT: «0␤»

Tight OR precedence

infix ||

Returns the first argument that evaluates to True in Boolean context, otherwise returns the last argument.

Note that this short-circuits; i.e., if one of the arguments evaluates to a true value, the remaining arguments are not evaluated.

sub a { 0 }
    sub b { 1 }
    sub c { die "never called" };
    say a() || b() || c();      # OUTPUT: «1␤»

infix ^^

Short-circuit exclusive-or. Returns the true argument if there is one (and only one). Returns the last argument if all arguments are false. Returns Nil when more than one argument is true.

This operator short-circuits in the sense that it does not evaluate any arguments after a 2nd true result.

say 0 ^^ 42;                             # OUTPUT: «42␤»
    say '' ^^ 0;                             # OUTPUT: «0␤»
    say 0 ^^ 42 ^^ 1 ^^ die "never called";  # OUTPUT: «Nil␤»

Note that the semantics of this operator may not be what you assume: infix ^^ flips to the first true value it finds and then flips to Nil forever after the second, no matter how many more true values there are. (In other words, it has "find the one true value" semantics, not "Boolean parity" semantics.)

infix //

The defined-or operator or infix // returns the first defined operand, or else the last operand. Short-circuits.

say Any // 0 // 42;         # OUTPUT: «0␤»

infix min

Returns the smallest of the arguments, as determined by cmp semantics.

my $foo = 42;
    $foo min= 0   # read as: $foo decreases to 0

Note: Before 2022.06, in the cases of ties &min would return the first argument with that value, whereas &[min] would return its RHS. After 2022.06, &[min] returns its LHS in the case of ties, and now both return the same value as dictated by their List associativity.

say min 0, False; # OUTPUT: «0␤»
    say 0 min False;  # OUTPUT: «0␤»
    say min False, 0; # OUTPUT: «False␤»
    say False min 0;  # OUTPUT: «False␤»

infix max

Returns the largest of the arguments, as determined by cmp semantics.

my $foo = -42;
    $foo max= 0   # read as: $foo increases to 0

Note: Before 2022.06, in the cases of ties &max would return the first argument with that value, whereas &[max] would return its RHS. After 2022.06, &[max] returns its LHS in the case of ties, and now both return the same value as dictated by their List associativity.

say max 0, False; # OUTPUT: «0␤»
    say 0 max False;  # OUTPUT: «0␤»
    say max False, 0; # OUTPUT: «False␤»
    say False max 0;  # OUTPUT: «False␤»

infix minmax

Returns the Range starting from the lowest to the highest of the values, as determined by the cmp semantics. For instance:

# numeric comparison
10 minmax 3;     # 3..10

# string comparison
'10' minmax '3'; # "10".."3"
'z' minmax 'k';  # "k".."z"

If the lowest and highest values coincide, the operator returns a Range made by the same value:

1 minmax 1;  # 1..1

When applied to Lists, the operator evaluates the lowest and highest values among all available values:

(10,20,30) minmax (0,11,22,33);       # 0..33
('a','b','z') minmax ('c','d','w');   # "a".."z"

Similarly, when applied to Hashes, it performs a cmp way comparison:

my %winner = points => 30, misses => 10;
my %loser = points => 20, misses => 10;
%winner cmp %loser;      # More
%winner minmax %loser;
# ${:misses(10), :points(20)}..${:misses(10), :points(30)}

Conditional operator precedence

infix ?? !!

Also called ternary or conditional operator, $condition ?? $true !! $false evaluates $condition and returns the expression right behind ??, in this case $true if it is True, otherwise evaluates and returns the expression behind !!, $false in this case.

infix ff

sub infix:<ff>(Mu $a, Mu $b)

Also called the flipflop operator, compares both arguments to $_ (that is, $_ ~~ $a and $_ ~~ $b). Evaluates to False until the left-hand smartmatch is True, at which point it evaluates to True until the right-hand smartmatch is True.

In effect, the left-hand argument is the "start" condition and the right-hand is the "stop" condition. This construct is typically used to pick up only a certain section of lines. For example:

my $excerpt = q:to/END/;
Here's some unimportant text.
=begin code
    This code block is what we're after.
    We'll use 'ff' to get it.
=end code
More unimportant text.
END

my @codelines = gather for $excerpt.lines {
    take $_ if "=begin code" ff "=end code"
}
# this will print four lines, starting with "=begin code" and ending with
# "=end code"
say @codelines.join("\n");

After matching the start condition, the operator will then match the same $_ to the stop condition and act accordingly if successful. In this example, only the first element is printed:

for <AB C D B E F> {
        say $_ if /A/ ff /B/;  # OUTPUT: «AB␤»
    }

If you only want to test against a start condition and have no stop condition, * can be used as such.

for <A B C D E> {
        say $_ if /C/ ff *;    # OUTPUT: «C␤D␤E␤»
    }

For the sed-like version, which does not try $_ on the stop condition after succeeding on the start condition, see fff.

This operator cannot be overloaded, as it's handled specially by the compiler.

infix ^ff

sub infix:<^ff>(Mu $a, Mu $b)

Works like ff, except it does not return True for items matching the start condition (including items also matching the stop condition).

A comparison:

my @list = <X A B C Y>;
    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ^ff /C/ for @list;   # OUTPUT: «B␤C␤»

The sed-like version can be found in ^fff.

This operator cannot be overloaded, as it's handled specially by the compiler.

infix ff^

sub infix:<ff^>(Mu $a, Mu $b)

Works like ff, except it does not return True for items matching the stop condition (including items that first matched the start condition).

my @list = <X A B C Y>;
    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ff^ /C/ for @list;   # OUTPUT: «A␤B␤»

The sed-like version can be found in fff^.

This operator cannot be overloaded, as it's handled specially by the compiler.

infix ^ff^

sub infix:<^ff^>(Mu $a, Mu $b)

Works like ff, except it does not return True for items matching either the stop or start condition (or both).

my @list = <X A B C Y>;
    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ^ff^ /C/ for @list;  # OUTPUT: «B␤»

The sed-like version can be found in ^fff^.

This operator cannot be overloaded, as it's handled specially by the compiler.

infix fff

sub infix:<fff>(Mu $a, Mu $b)

Performs a sed-like flipflop operation, wherein it returns False until the left argument smartmatches against $_, then returns True until the right argument smartmatches against $_.

Works similarly to ff, except that it only tries one argument per invocation. That is, if $_ smartmatches the left argument, fff will not then try to match that same $_ against the right argument.

for <AB C D B E F> {
        say $_ if /A/ fff /B/;         # OUTPUT: «AB␤C␤D␤B␤»
    }

The non-sed-like flipflop (which after successfully matching the left argument against $_ will try that same $_ against the right argument and act accordingly). See ff.

This operator cannot be overloaded, as it's handled specially by the compiler.

infix ^fff

sub infix:<^fff>(Mu $a, Mu $b)

Like fff, except it does not return true for matches to the left argument.

my @list = <X A B C Y>;
    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ^fff /C/ for @list;  # OUTPUT: «B␤C␤»

For the non-sed version, see ^ff.

This operator cannot be overloaded, as it's handled specially by the compiler.

infix fff^

sub infix:<fff^>(Mu $a, Mu $b)

Like fff, except it does not return true for matches to the right argument.

my @list = <X A B C Y>;
    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ fff^ /C/ for @list;  # OUTPUT: «A␤B␤»

For the non-sed version, see ff^.

This operator cannot be overloaded, as it's handled specially by the compiler.

infix ^fff^

sub infix:<^fff^>(Mu $a, Mu $b)

Like fff, except it does not return true for matches to either the left or right argument.

my @list = <X A B C Y>;
    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ^fff^ /C/ for @list; # OUTPUT: «B␤»

For the non-sed version, see ^ff^.

This operator cannot be overloaded, as it's handled specially by the compiler.

Item assignment precedence

infix = (item assignment)

sub infix:<=>(Mu $a is rw, Mu $b)

Called the item assignment operator. It copies the value of the right-hand side into the Scalar container on the left-hand side.

The item assignment operator should be distinguished from the list assignment operator, which uses the same operator symbol = but has a lower precedence. The context of the left-hand side of the = symbol determines whether it is parsed as item assignment or list assignment. See the section on item and list assignment for a comparative discussion of the two assignment types.

infix =>

sub infix:«=>»($key, Mu $value --> Pair:D)

Pair constructor.

Constructs a Pair object with the left-hand side as the key and the right-hand side as the value.

Note that the => operator is syntactically special-cased, in that it allows unquoted identifier on the left-hand side.

my $p = a => 1;
    say $p.key;         # OUTPUT: «a␤»
    say $p.value;       # OUTPUT: «1␤»

A Pair within an argument list with an unquoted identifier on the left is interpreted as a named argument.

See the Terms language documentation for more ways to create Pair objects.

Loose unary precedence

prefix not

multi prefix:<not>(Mu $x --> Bool:D)

Evaluates its argument in Boolean context (and thus collapses Junctions), and negates the result. Please note that not is easy to misuse. See traps.

prefix so

multi prefix:<so>(Mu $x --> Bool:D)

Evaluates its argument in Boolean context (and thus collapses Junctions), and returns the result.

Comma operator precedence

infix ,

sub infix:<,>(*@a --> List:D) is assoc<list>

Constructs a higher-order Cool from its arguments.

my @list = :god('Þor'), ['is',"mighty"];
    say @list;      # OUTPUT: «[god => Þor [is mighty]]␤»
    my %hash = :god('Þor'), :is("mighty");
    say %hash.raku; # OUTPUT: «{:god("Þor"), :is("mighty")}␤»
    my %a = :11a, :22b;
    say %(%a, :33x);  # OUTPUT: «{a => 11, b => 22, x => 33}␤»

In the first case it returns a List, in the second case, since the arguments are Pairs, it builds a Hash.

It can also be used for constructing variables from other variables, collating elements of different types, in this case a Hash and a Pair:

my %features = %hash, :wields("hammer");
say %features;  # OUTPUT: «{god => Þor, is => mighty, wields => hammer}␤»

The comma is also used syntactically as the separator of arguments in calls.

infix :

Used as an argument separator just like infix , and marks the argument to its left as the invocant. That turns what would otherwise be a function call into a method call.

substr('abc': 1);       # same as 'abc'.substr(1)

Infix : is only allowed after the first argument of a non-method call. In other positions, it's a syntax error.

List infix precedence

infix Z

sub infix:<Z>(**@lists --> Seq:D) is assoc<list>

The Zip operator interleaves the lists passed to Z like a zipper, taking index-corresponding elements from each operand. The returned Seq contains nested lists, each with a value from every operand in the chain. If one of the operands runs out of elements prematurely, the zip operator will stop.

say (1, 2 Z <a b c> Z <+ ->).raku;
# OUTPUT: «((1, "a", "+"), (2, "b", "-")).Seq␤»
for <a b c> Z <1 2 3 4> -> [$l, $r] {
    say "$l:$r"
}
# OUTPUT: «a:1␤b:2␤c:3␤»

The Z operator also exists as a metaoperator, in which case the inner lists are replaced by the value from applying the operator to the list:

say 100, 200 Z+ 42, 23;             # OUTPUT: «(142 223)␤»
    say 1..3 Z~ <a b c> Z~ 'x' xx 3;    # OUTPUT: «(1ax 2bx 3cx)␤»

As any other infix operator, it can be used under its full name:

say infix:<Z>(<a b>,<c d>);             # OUTPUT: «((a c) (b d))␤»

If no argument is given, it will return an empty Seq

say infix:<Z>();                        # OUTPUT: «()␤»

infix X

multi infix:<X>(+lol, :&with! --> Seq:D)
    multi infix:<X>(+lol --> Seq:D)

Creates a cross product from all the lists, ordered so that the rightmost elements vary most rapidly, and returns a Seq:

1..3 X <a b c> X 9
    # produces ((1 a 9) (1 b 9) (1 c 9)
    #           (2 a 9) (2 b 9) (2 c 9)
    #           (3 a 9) (3 b 9) (3 c 9))

The X operator also exists as a metaoperator, in which case the inner lists are replaced by the value from applying the operator to the list:

1..3 X~ <a b c> X~ 9
    # produces (1a9 1b9 1c9 2a9 2b9 2c9 3a9 3b9 3c9)

infix ...

multi infix:<...>(**@) is assoc<list>
    multi infix:<...^>(**@) is assoc<list>
    multi infix:<^...>(**@) is assoc<list>
    multi infix:<^...^>(**@) is assoc<list>

The sequence operator, which can be written either as ... or as , with variants ...^, ^..., ^...^, …^, ^… and ^…^, will produce (possibly lazy) generic sequences on demand. Such sequences are of the Seq type.

The variants of the operator with an initial caret, ^..., ^...^, ^… and ^…^, produce sequences that do not contain the initial element.

The variants of the operator with a final caret, ...^, ^...^, …^ and ^…^, produce sequences that do not contain the final element.

Note: the variants ^..., ^...^, ^… and ^…^ have been available in Rakudo compiler starting from 2020.05 release.

The left-hand side of the operator specify the initial elements; it may include a generator after the first element or elements. The right-hand side will have an endpoint, which can be Inf or * for "infinite" lists (that is, lazy lists whose elements are only produced on demand), an expression which will end the sequence when True, or other elements such as Junctions.

The sequence operator invokes the generator with as many arguments as necessary. The arguments are taken from the initial elements and the already generated elements.

An endpoint of * (Whatever), Inf or generates on demand an infinite sequence, with a default generator of *.succ

say (1 ... *)[^5];  # OUTPUT: «(1 2 3 4 5)␤»

Custom generators need to be the last element of the list before the '...' operator. This one takes two arguments, and generates the eight first Fibonacci numbers

say (1, 1, -> $a, $b { $a + $b } ... *)[^8]; # OUTPUT: «(1 1 2 3 5 8 13 21)␤»
# same but shorter
say (1, 1, * + * ... *)[^8];                 # OUTPUT: «(1 1 2 3 5 8 13 21)␤»

The generator can also take only one argument.

say 5, { $_ * 2 } ... 40;                # OUTPUT: «5 10 20 40␤»

Or it can use the anonymous state variable $ to skip one position in the sequence when computing the next one:

say (1, 1, 1, -> $a, $b, $ { $a + $b } … ∞)[3..10];
    # OUTPUT: «(2 2 3 4 5 7 9 12)␤»

There must be at least as many initial elements as arguments to the generator.

If the endpoint is not *, it's smartmatched against each generated element and the sequence is terminated when the smartmatch succeeded. The final element is excluded of the sequence if a sequence operator variant with a final caret is used, it is included otherwise.

This allows you to write

say 1, 1, * + * ...^ *>= 100;
    # OUTPUT: «(1 1 2 3 5 8 13 21 34 55 89)␤»

to generate all Fibonacci numbers up to but excluding 100.

The ... operators consider the initial values as "generated elements" as well, so they are also checked against the endpoint:

my $end = 4;
    say 1, 2, 4, 8, 16 ... $end;
    # OUTPUT: «(1 2 4)␤»

If you do not provide a generator, the sequence operator tries to deduce the sequence. In most cases, this means using a default *.succ or *.pred, depending on how the end points compare:

say 1 ... 4;        # OUTPUT: «(1 2 3 4)␤»
    say 4 ... 1;        # OUTPUT: «(4 3 2 1)␤»
    say 1 ^... 4;       # OUTPUT: «(2 3 4)␤»
    say 1 ...^ 4;       # OUTPUT: «(1 2 3)␤»
    say 1 ^...^ 4;      # OUTPUT: «(2 3)␤»
    say 'a' ... 'e';    # OUTPUT: «(a b c d e)␤»
    say 'e' ... 'a';    # OUTPUT: «(e d c b a)␤»

However, the sequence operator will deduce a different sequence in some special cases.

If you provide more than one initial element and all initial elements are numeric, the sequence operator tries find an arithmetic or geometric sequence that fits the pattern in the initial elements:

say 2, 4, 6 ... 12;     # OUTPUT: «(2 4 6 8 10 12)␤»
    say 1, 2, 4 ... 32;     # OUTPUT: «(1 2 4 8 16 32)␤»
    say 1, 2, 4 ^... 32;    # OUTPUT: «(2 4 8 16 32)␤»
    say 1, 2, 4 ^...^ 32;   # OUTPUT: «(2 4 8 16)␤»

If you provide one Str initial element and a Str final element with the same number of characters, then the sequence operator will deduce a sequence of all strings where each letter is le the letter at the corresponding position in the final element:

say 'aa' … 'cc';          # OUTPUT: «(aa ab ac ba bb bc ca cb cc)␤»
    # Which is the same as
    say 'a'..'c' X~ 'a'..'c'; # OUTPUT: «(aa ab ac ba bb bc ca cb cc)␤»

List prefix precedence

infix = (list assignment)

The list assignment operator generally copies values from its right-hand side into the container on its left-hand side. Its exact semantics are left to the left-hand side container type. See Array and Hash for common cases.

The list assignment operator should be distinguished from the item assignment operator, which uses the same operator symbol = but has a higher precedence. The context of the left-hand side of the = symbol determines whether it is parsed as item assignment or list assignment. See the section on item and list assignment for a comparative discussion of the two assignment types.

infix :=

Binding operator. Whereas $x = $y puts the value in $y into $x, $x := $y makes $x and $y the same thing.

my $a = 42;
    my $b = $a;
    $b++;
    say $a;

This will output 42, because $a and $b both contained the number 42, but the containers were different.

my $a = 42;
    my $b := $a;
    $b++;
    say $a;

This will output 43, since $b and $a both represented the same object.

If type constrains on variables or containers are present a type check will be performed at runtime. On failure X::TypeCheck::BindingType will be thrown.

Please note that := is a compile time operator. As such it can not be referred to at runtime and thus can't be used as an argument to metaoperators.

infix ::=

Read-only binding operator, not yet implemented in Rakudo. See infix :=.

listop ...

Called the yada, yada, yada operator or stub operator, if it's the only statement in a routine or type, it marks that routine or type as a stub (which is significant in the context of pre-declaring types and composing roles).

If the ... statement is executed, it calls fail, with the default message Stub code executed.

This operator can be used for forward declarations of classes:

class Foo {...}
class Bar {
    has Foo $.foo;
}
class Foo {
    say "This is a Foo object";
}

or routines, such as this Sub:

sub a() { ... }
say a;           # OUTPUT: «42␤»
sub a() { 42 }

Please note that, in this case, it's not really necessary, and it will work the same without that forward declaration.

listop !!!

If it's the only statement in a routine or type, it marks that routine or type as a stub (which is significant in the context of pre-declaring types and composing roles).

If the !!! statement is executed, it calls die, with the default message Stub code executed.

listop ???

If it's the only statement in a routine or type, it marks that routine or type as a stub (which is significant in the context of pre-declaring types and composing roles).

If the ??? statement is executed, it calls warn, with the default message Stub code executed.

Reduction operators

Any infix operator (except for non-associating operators) can be surrounded by square brackets in term position to create a list operator that reduces using that operation.

say [+] 1, 2, 3;      # 1 + 2 + 3 = 6
    my @a = (5, 6);
    say [*] @a;           # 5 * 6 = 30

Reduction operators have the same associativity as the operators they are based on.

say [-] 4, 3, 2;      # 4-3-2 = (4-3)-2 = -1
    say [**] 4, 3, 2;     # 4**3**2 = 4**(3**2) = 262144

Applying [+] to a single element will return that element

say [+] 42;           # OUTPUT: «42␤»

Loose AND precedence

infix C«and|Operators,and>

Same as infix &&, except with looser precedence.

Short-circuits so that it returns the first operand that evaluates to False, otherwise returns the last operand. Note that and is easy to misuse, see traps.

infix C«andthen|Operators,andthen>

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 the with statement modifier, and some compilers compile with to andthen, meaning these two lines have equivalent behavior:

.say with 42;
    42 andthen .say;

infix C«notandthen|Infix operators,notandthen>

The notandthen operator returns Empty upon encountering the first defined 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.

At first glance, notandthen might appear to be the same thing as the orelse operator. The difference is subtle: notandthen returns Empty when it encounters a defined item (that isn't the last item), whereas orelse returns that item. In other words, notandthen is a means to act when items aren't defined, whereas orelse is a means to obtain the first defined item:

sub all-sensors-down     { [notandthen] |@_, True             }
sub first-working-sensor { [orelse]     |@_, 'default sensor' }

all-sensors-down Nil, Nil, Nil
  and say 'OMG! All sensors are down!'; # OUTPUT:«OMG! All sensors are down!␤»
say first-working-sensor Nil, Nil, Nil; # OUTPUT:«default sensor␤»

all-sensors-down Nil, 42, Nil
  and say 'OMG! All sensors are down!'; # No output
say first-working-sensor Nil, 42, Nil;  # OUTPUT:«42␤»

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

sub good-things { fail }

'boo'.say without good-things;
good-things() notandthen 'boo'.say;

Loose OR precedence

infix or

Same as infix ||, except with looser precedence.

Returns the first argument that evaluates to True in Boolean context, or otherwise the last argument, it short-circuits. Please note that or is easy to misuse. See traps.

infix orelse

The orelse operator is similar to infix //, except with looser precedence and $_ aliasing.

Returns the first defined argument, or else 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 an argument if the right side is a Callable, whose count must be 0 or 1.

This operator is useful for handling Failures returned by routines since the expected value is usually defined and Failure never is:

sub meows { ++$ < 4 ?? fail 'out of meows!' !! '🐱' }
sub meows-processor1 { meows() orelse .return } # return handled Failure
    sub meows-processor2 { meows() orelse fail $_ } # return re-armed Failure
    sub meows-processor3 {
        # Use non-Failure output, or else print a message that stuff's wrong
        meows() andthen .say orelse ‘something's wrong’.say;
    }
say "{.^name}, {.handled}"  # OUTPUT: «Failure, True␤»
        given meows-processor1;
    say "{.^name}, {.handled}"  # OUTPUT: «Failure, False␤»
        given meows-processor2;
    meows-processor3;           # OUTPUT: «something's wrong␤»
    meows-processor3;           # OUTPUT: «🐱␤»

infix xor

Same as infix ^^, except with looser precedence.

Returns the operand that evaluates to True in Boolean context, if and only if the other operand evaluates to False in Boolean context. If both operands evaluate to False, returns the last argument. If both operands evaluate to True, returns Nil.

When chaining, returns the operand that evaluates to True, if and only if there is one such operand. If more than one operand is true, it short-circuits after evaluating the second and returns Nil. If all operands are false, returns the last one.

Sequencer precedence

infix ==>

This feed operator takes the result from the left and passes it to the next (right) routine as the last parameter.

my @array = (1, 2, 3, 4, 5);
     @array ==> sum() ==> say();   # OUTPUT: «15␤»

This simple example, above, is the equivalent of writing:

my @array = (1, 2, 3, 4, 5);
     say(sum(@array));             # OUTPUT: «15␤»

Or if using methods:

my @array = (1, 2, 3, 4, 5);
     @array.sum.say;               # OUTPUT: «15␤»

The precedence is very loose so you will need to use parentheses to assign the result or you can even just use another feed operator! In the case of routines/methods that take a single argument or where the first argument is a block, it's often required that you call with parentheses (though this is not required for the very last routine/method).

This "traditional" structure, read bottom-to-top, with the last two lines creating the data structure that is going to be processed

my @fractions = <TWO THREE FOUR FIVE SEVEN> »~» " " X~ <FIFTHS SIXTHS EIGHTHS>;
    my @result = map { .uniparse },                    # (3) Converts to unicode
        grep { .uniparse },                            # (2) Checks if it parses
        map( {"VULGAR FRACTION " ~ $^þ }, @fractions); # (1) Adds string to input
# @result is [⅖ ⅗ ⅜ ⅘ ⅚ ⅝ ⅞]

Now we use the feed operator (left-to-right) with parentheses, read top-to-bottom

my @result = (
        <TWO THREE FOUR FIVE SEVEN> »~» " " X~ <FIFTHS SIXTHS EIGHTHS> # (1) Input
        ==> map( {"VULGAR FRACTION " ~ $^þ } )                         # (2) Converts to Unicode name
        ==> grep({ .uniparse })                                        # (3) Filters only real names
        ==> map( { .uniparse} );                                       # (4) Converts to unicode
    );

For illustration, method chaining equivalent, read top-to-bottom, using the same sequence as above

my @result = ( <TWO THREE FOUR FIVE SEVEN> »~» " " X~ <FIFTHS SIXTHS EIGHTHS>)
        .map( {"VULGAR FRACTION " ~ $^þ } )
        .grep({ .uniparse })
        .map({ .uniparse });

Although in this particular case the result is the same, the feed operator ==> more clearly shows intent with arrow pointing in the direction of the data flow. To assign without the need of parentheses use another feed operator

<people of earth>
        ==> map({ .tc })
        ==> grep /<[PE]>/
        ==> sort()
        ==> my @result;

It can be useful to capture a partial result, however, unlike the leftward feed operator, it does require parentheses or a semicolon

<people of earth>
        ==> map({ .tc })
        ==> my @caps; @caps   # also could wrap in parentheses: (my @caps)
        ==> grep /<[PE]>/
        ==> sort()
        ==> my @result;

The feed operator lets you construct method-chaining-like patterns out of routines and the results of methods on unrelated data. In method-chaining, you are restricted to the methods available on the data or the result of previous method call. With feed operators, that restriction is gone. The resulting code could also be seen to be more readable than a series of method calls broken over multiple lines.

Note: In the future, this operator will see some change as it gains the ability to run list operations in parallel. It will enforce that the left operand is enclosable as a closure (that can be cloned and run in a subthread).

infix <==

This leftward feed operator takes the result from the right and passes it to the previous (left) routine as the last parameter. This elucidates the right-to-left dataflow for a series of list manipulating functions.

# Traditional structure, read bottom-to-top
    my @result =
        sort                   # (4) Sort, result is <Earth People>
        grep { /<[PE]>/ },     # (3) Look for P or E
        map { .tc },           # (2) Capitalize the words
        <people of earth>;     # (1) Start with the input
# Feed (right-to-left) with parentheses, read bottom-to-top
    my @result = (
        sort()                 # (4) Sort, result is <Earth People>
        <== grep({ /<[PE]>/ }) # (3) Look for P or E
        <== map({ .tc })       # (2) Capitalize the words
        <== <people of earth>  # (1) Start with the input
    );
# To assign without parentheses, use another feed operator
    my @result
        <== sort()              # (4) Sort, result is <Earth People>
        <== grep({ /<[PE]>/ })  # (3) Look for P or E
        <== map({ .tc })        # (2) Capitalize the words
        <== <people of earth>;  # (1) Start with the input
# It can be useful to capture a partial result
    my @result
        <== sort()
        <== grep({ /<[PE]>/ })
        <== my @caps            # unlike ==>, there's no need for additional statement
        <== map({ .tc })
        <== <people of earth>;

Unlike the rightward feed operator, the result is not closely mappable to method-chaining. However, compared to the traditional structure above where each argument is separated by a line, the resulting code is more demonstrative than commas. The leftward feed operator also allows you to "break into" the statement and capture an intermediary result which can be extremely useful for debugging or to take that result and create another variation on the final result.

Note: In the future, this operator will see some change as it gains the ability to run list operations in parallel. It will enforce that the right operand is enclosable as a closure (that can be cloned and run in a subthread).

Identity

In general, infix operators can be applied to a single or no element without yielding an error, generally in the context of a reduce operation.

say [-] ()  # OUTPUT: «0␤»

The design documents specify that this should return an identity value, and that an identity value must be specified for every operator. In general, the identity element returned should be intuitive. However, here is a table that specifies how it is defined for operator classes in Raku, which corresponds to the table in the above definition in the types and operators defined by the language:

Operator class Identity value
Equality True
Arithmetic \+ 0
Arithmetic * 1
Comparison True
Bitwise 0
Stringy ''
Sets Empty set or equivalent
Or-like Bool False
And-like Bool True

For instance, union of an empty list will return an empty set:

say [∪];  # OUTPUT: «Set()␤»

This only applies to operators where empty or 0 is always a valid operand. For instance, applying it to division will yield an exception.

say [%] ();  # OUTPUT: «(exit code 1) No zero-arg meaning for infix:<%>␤»

See Also

Containers

A low-level explanation of Raku containers

Contexts and contextualizers

What are contexts and how to switch into them

Control flow

Statements used to control the flow of execution

Enumeration

An example using the enum type

Exceptions

Using exceptions in Raku

Functions

Functions and functional programming in Raku

Grammars

Parsing and interpreting text

Hashes and maps

Working with associative arrays/dictionaries/hashes

Input/Output the definitive guide

Correctly use Raku IO

Lists, sequences, and arrays

Positional data constructs

Metaobject protocol (MOP)

Introspection and the Raku object system

Native calling interface

Call into dynamic libraries that follow the C calling convention

Raku native types

Using the types the compiler and hardware make available to you

Newline handling in Raku

How the different newline characters are handled, and how to change the behavior

Numerics

Numeric types available in Raku

Object orientation

Object orientation in Raku

Packages

Organizing and referencing namespaced program elements

Performance

Measuring and improving runtime or compile-time performance

Phasers

Program execution phases and corresponding phaser blocks

Pragmas

Special modules that define certain aspects of the behavior of the code

Quoting constructs

Writing strings and word lists, in Raku

Regexes

Pattern matching against strings

Sets, bags, and mixes

Unordered collections of unique and weighted objects in Raku

Signature literals

A guide to signatures in Raku

Statement prefixes

Prefixes that alter the behavior of a statement or a set of them

Data structures

How Raku deals with data structures and what we can expect from them

Subscripts

Accessing data structure elements by index or key

Syntax

General rules of Raku syntax

System interaction

Working with the underlying operating system and running applications

Date and time functions

Processing date and time in Raku

Traits

Compile-time specification of behavior made easy

Unicode versus ASCII symbols

Unicode symbols and their ASCII equivalents

Unicode

Unicode support in Raku

Variables

Variables in Raku

Independent routines

Routines not defined within any class or role.

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.