Operators

Common Perl 6 infixes, prefixes, postfixes, and more!

Operator Precedence

In an expression like 1 + 2 * 3, the 2 * 3 is evaluated first because the infix * has tighter precedence than the +.

The following table summarizes the precedence levels in Perl 6, from tightest to loosest:

A Level Examples
N Terms 42 3.14 "eek" qq["foo"] $x :!verbose @$array
L Method postfix .meth .+ .? .* .() .[] .{} .<> .«» .:: .= .^ .:
N Autoincrement ++ --
R Exponentiation **
L Symbolic unary ! + - ~ ? | || +^ ~^ ?^ ^
L Multiplicative * / % %% +& +< +> ~& ~< ~> ?& div mod gcd lcm
L Additive + - +| +^ ~| ~^ ?| ?^
L Replication x xx
X Concatenation ~
X Junctive and &
X Junctive or | ^
L Named unary temp let
N Structural infix but does <=> leg cmp .. ..^ ^.. ^..^
C Chaining infix != == < <= > >= eq ne lt le gt ge ~~ === eqv !eqv =~=
X Tight and &&
X Tight or || ^^ // min max
R Conditional ?? !! ff fff
R Item assignment = => += -= **= xx= .=
L Loose unary so not
X Comma operator , :
X List infix Z minmax X X~ X* Xeqv ...
R List prefix print push say die map substr ... [+] [*] any Z=
X Loose and and andthen
X Loose or or xor orelse
X Sequencer <==, ==>, <<==, ==>>
N Terminator ; {...}, unless, extra ), ], }

Using two ! symbols below generically to represent any pair of operators that have the same precedence, the associativities specified above for binary operators are interpreted as follows:

A Assoc Meaning of $a ! $b ! $c
L left ($a ! $b) ! $c
R right $a ! ($b ! $c)
N non ILLEGAL
C chain ($a ! $b) and ($b ! $c)
X list infix:<!>($a; $b; $c)

For unary operators this is interpreted as:

A Assoc Meaning of !$a!
L left (!$a)!
R right !($a!)
N non ILLEGAL

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

Each operator is also available as a subroutine. The name of the routine is formed of the operator category, then a colon, and 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 meta-reduced infix operators ([+] 1, 2, 3) and the prefix ... etc. stub operators.

Defining custom operators is covered in Defining Operators functions.

Meta Operators

Meta operators can be parameterized with other operators or subroutines in the same way as functions can take functions as parameters. To use a subroutine as a parameter prefix it's name with a &. Perl 6 will generate the actual combined operator in the background, allowing the mechanism to be applied to user defined operators. There are quite a few Meta operators with different semantics, as explained in detail as follows.

Substitution Operators

my $str = 'match string';
$str ~~ s/match/replacement/;
say $str; # replacement string

say S/match/replacement/ given 'match string'; # replacement string

The lower-case version (s///) substitutes in-place, while the upper-case version (S///) leaves the original alone and returns the resultant string.

Both operators work on `$_` variable. Since smartmatch operator aliases the left hand side to `$_`, you can use lowercase `s///` with it, but it's a mistake to use it with uppercase `S///`, because you can't retrieve the modified string. The correct way is to alias the given string by some other method, such as a `for` loop or, as is shown in the example above, with a `given` block (in this case, it's a postfix form of it, without curlies).

Both operators can take the same adverbs as the .subst method, which go between the `s`/`S` and the opening `/`. Whitespace can be used liberally:

my $str = 'match string';
$str ~~ s:g/match/replacement/;
say S:i :g /match/replacement/ given 'match string';

You can also use a different delimiter:

my $str = 'foobar';
$str ~~ s!foo!!;
say S{foo} = {} given 'foobar';

Non-matching characters can simply replace the original slashes. Matching characters, like braces, require an extra step where you use an assignment operator to assign the replacement to the match part.

Assignment Operators

Infix operators can be combined with the assignment operator to modify a value and apply the result to a container in one go. Containers will be autovivified if possible.

my $a = 32;
$a += 10;  # 42

$a = 3;
$a min= 5; # still 3
$a min= 2; # 2

This behavior is automatically extended to include custom-defined infix operators.

sub infix:<space-concat> ($a, $b) { $a ~ " " ~ $b };
my $a = 'word1';
$a space-concat= 'word2'; # 'word1 word2'

Although not strictly operators, methods can be used in the same fashion.

my Real $a = 1/2;
$a = 3.14;
$a .= round; # 3

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; # False
my $i = 10;

my $release = Date.new(:2015year, :12month, :24day);
my $today = Date.today;
say so $release !before $today; # True

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; # 3
say [R/] 2, 4, 16; # 2

Hyper Operators

Hyper operators apply a given operator enclosed by « and » to one or two lists, returning the resulting list. The pointy part of « or » has to point to the shorter list. A list with just one element is fine too. If one of the lists is shorter then the other, the operator will cycle over the shorter list until all elements of the longer list are processed.

say (1, 2, 3) »*» 2;          # (2 4 6)
say (1, 2, 3, 4) »~» <a b>;   # (1a 2b 3a 4b)
say (1, 2, 3) »+« (4, 5, 6);  # (5 7 9)

Assignment meta operators can be hyped.

my @a = 1, 2, 3;
say @a »+=» 1; # [2 3 4]

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

my @wisdom = True, False, True;
say@wisdom; # [False True False]

my @a = 1, 2, 3;
@a»++;           # (2, 3, 4)

Hyper operators are defined recursively on nested arrays.

say -« [[1, 2], 3]; # [[-1 -2] -3]

Methods can be called too, in an out of order, concurrent fashion. The resulting list is in order. Please note that all hyper operators are candidates for autothreading and will cause tears if said methods have side effects. The optimizer has full reign over hyper operators, which is the reason that they can not 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; # {"1" => "ax", "2" => "bz"}

Hyper operators can take user defined operators as its operator argument.

sub pretty-file-site (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-site(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»

Hyper operators do not descent into child lists. 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, *); # ((1 3) (2 2) (2 4) (3 3))

Reduction Operators

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;           # 6
say reduce &[+], 1, 2, 3;  # 6

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

sub plus { $^a + $^b };
say [[&plus]] 1, 2, 3;  # 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>;  # 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];  # (1 12 123 1234 12345)

Cross Operators

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

1..3 X~ <a b>
# produces <1a, 1b, 2a, 2b, 3a, 3b>

Zip Operators

The zip metaoperator, 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; # [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 *; # <a: b: c: d:>
   @l = <a b c d> Z~ 1, 2, *;  # <a1 b2 c2 d2>

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

my @l = 1 Z 2; # [(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; # True

Nesting of Meta Operators

To avoid ambiguity when chaining meta operators use square brackets to help the compiler to understand you.

my @a = 1, 2, 3;
my @b = 5, 6, 7;
@a X[+=] @b;
say @a; # [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 is converted to the appropriate number.

say <a b c>[1];     # b

term ( )

The grouping operator.

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

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

multi sub p(:$a!) { say 'named'      }
multi sub p($a)   { say 'positional' }
p a => 1;       # named
p (a => 1);     # positional

term { }

Block or Hash constructor.

If the contents looks like a list of pairs and does not use $_ or other placeholder parameters, returns an itemized Hash.

Otherwise it constructs a Block.

Note that this construct does not re-parse the contents; rather the contents are always parsed as a statement list (i.e. like a block), and if the later analysis shows that it needs to be interpreted as a hash, the block is executed and coerced to Hash.

circumfix [ ]

The Array constructor. Returns an itemized Array which does not flatten in list context.

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 a @container, a.k.a. "array indexing operator".

my @alphabet = 'a' .. 'z';
say @alphabet[0];                   #-> a
say @alphabet[1];                   #-> b
say @alphabet[*-1];                 #-> z
say @alphabet[100]:exists;          #-> False
say @alphabet[15, 4, 17, 11].join;  #-> perl
say @alphabet[23 .. *].perl;        #-> ("x", "y", "z")

@alphabet[1, 2] = "B", "C";
say @alphabet[0..3].perl            #-> ("a", "B", "C", "d")

See Subscripts for a more detailed explanation of this operator's behavior, and 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"};               #-> yellow
say %color{"cherry", "kiwi"}.perl;  #-> ("red", "green")
say %color{"strawberry"}:exists;    #-> False

%color{"banana", "lime"} = "yellowish", "green";
%color{"cherry"}:delete;
say %color;  #-> banana => yellowish, kiwi => green, lime => green

See postcircumfix < > and 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 < >

Shortcut for postcircumfix { } that quotes its argument using the same rules as the quote-words operator of the same name.

my %color = kiwi => "green", banana => "yellow", cherry => "red";
say %color<banana>;             #-> yellow
say %color<cherry kiwi>.perl;   #-> ("red", "green")
say %color<strawberry>:exists;  #-> False

This is not a real operator, just syntactic sugar that is 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 of the same name.

my %color = kiwi => "green", banana => "yellow", cherry => "red";
my $fruit = "kiwi";
say %color«cherry $fruit».perl;   #-> ("red", "green")

This is not a real operator, just syntactic sugar that is 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 parens as arguments.

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

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

postfix .

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

Technically this is not an operator, but syntax special-cased in the compiler.

postfix .&

The operator to call a subroutine (with at least one positional argument) like a method. The invocant will be bound to the first positional argument.

Technically this is not an operator, but syntax special-cased in the compiler.

my sub f($invocant){ dd $invocant; }
my $i = 42;
42.&f;
# OUTPUT«Int $invocant = 42␤»
42.&(-> $invocant { dd $invocant });
# OUTPUT«Int $invocant = 42␤»

postfix .=

A mutating method call. $invocant.=method desugars to $invocant = $invocant.method, similar to =.

Technically this is not an operator, but syntax special-cased in the compiler.

postfix .^

A meta-method call. $invocant.^method calls method on $invocant's metaclass. It desugars to $invocant.HOW.method($invocant, ...). See HOW for more information.

Technically this is not an operator, but syntax special-cased in the compiler.

postfix .?

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

Technically this is not an operator, but syntax special-cased in the compiler.

postfix .+

$invocant.+method calls all methods called method from $invocant, and returns a List of the results. Dies if no such method was found.

Technically this is not an operator, but syntax special-cased in the compiler.

postfix .*

$invocant.*method calls all methods called method from $invocant, and returns a List of the results. If no such method was found, an empty List is returned.

Technically this is not an operator, but syntax special-cased in the compiler.

postfix ». / postfix >>.

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

postfix .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); # 3
# OR
say $addition.function.(1, 2); # 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 this is not an operator, but syntax special-cased in the compiler.

postfix .:<prefix>

A prefix can be called like a method using colonpair notation. For example:

my $a = 1;
say ++$a;     # 2
say $a.:<++>; # 3

Technically this is not an operator, but syntax special-cased in the compiler.

postfix .::

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; # 42

Autoincrement Precedence

prefix ++

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

Increments its argument by one, and returns the incremented value.

my $x = 3;
say ++$x;       # 4
say $x;         # 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 --

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

Decrements its argument by one, and returns the decremented value.

my $x = 3;
say --$x;       # 2
say $x;         # 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 ++

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

Increments its argument by one, and returns the unincremented value.

my $x = 3;
say $x++;       # 3
say $x;         # 4

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

Note that this does not necessarily return its argument. For example for undefined values, it returns 0:

my $x;
say $x++;       # 0
say $x;         # 1

postfix --

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

Decrements its argument by one, and returns the undecremented value.

my $x = 3;
say $x--;       # 3
say $x;         # 2

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

Note that this does not necessarily return its argument. For example for undefined values, it returns 0:

my $x;
say $x--;       # 0
say $x;         # -1

Exponentiation Precedence

infix **

multi sub infix:<**>(Any, Any) returns 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.

Symbolic Unary Precedence

prefix ?

multi sub prefix:<?>(Mu) returns Bool:D

Boolean context operator.

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

prefix !

multi sub prefix:<!>(Mu) returns 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 sub prefix:<+>(Any) returns Numeric:D

Numeric context operator.

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

prefix -

multi sub prefix:<->(Any) returns 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 sub prefix:<~>(Any) returns 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.

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 sub prefix:<+^>(Any) returns Int:D

Integer bitwise negation operator.

Coerces the argument to Int and does a bitwise negation on the result, assuming two's complement.

prefix ?^

multi sub prefix:<?^>(Mu) returns 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 sub prefix:<^>(Any) returns Range:D

upto operator.

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

say ^5;         # 0..^5
for ^5 { }      # 5 iterations

Multiplicative Precedence

infix *

multi sub infix:<*>(Any, Any) returns 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 sub infix:</>(Any, Any) returns 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.

infix div

multi sub infix:<div>(Int:D, Int:D) returns Int:D

Integer division operator. Rounds down.

infix %

multi sub infix:<%>($x, $y) return 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

infix %%

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

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

infix mod

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

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

infix +&

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

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

infix +<

multi sub infix:<< +< >>($a, $b) returns Int:D

Integer bit shift to the left.

infix +>

multi sub infix:<< +> >>($a, $b) returns Int:D

Integer bit shift to the right.

infix gcd

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

Coerces both arguments to Int and returns the greatest common divisor.

infix lcm

multi sub infix:<lcm>($a, $b) returns 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 sub infix:<+>($a, $b) returns Numeric:D

Addition operator.

Coerces both arguments to Numeric and adds them.

infix -

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

Subtraction operator.

Coerces both arguments to Numeric and subtracts the second from the first.

infix +|

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

Integer bitwise OR operator.

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

infix +^

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

Integer bitwise XOR operator.

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

infix ?|

multi sub infix:<?|>($a, $b) returns Bool:D

Boolean logical OR operator.

Coerces both arguments to Bool and does a logical OR (inclusive OR) operation.

Replication Precedence

infix x

proto sub infix:<x>(Any, Any) returns Str:D
multi sub infix:<x>(Any, Any)
multi sub infix:<x>(Str:D, Int:D)

String repetition operator.

Coerces $a to Str and $b to Int and repeats the string $b times. Return the empty string if $b <= 0 .

say 'ab' x 3;       # ababab
say 42 x 3;         # 424242

infix xx

multi sub infix:<xx>($a, $b) returns List:D

List repetition operator.

Returns a list of $a repeated and evaluated $b times ($b is coerced to Int). If $b <= 0 , the empty list is returned.

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.

Concatenation

infix ~

proto sub infix:<~>(Any, Any) returns Str:D
multi sub infix:<~>(Any,   Any)
multi sub infix:<~>(Str:D, Str:D)

String concatenation operator.

Coerces both arguments to Str and concatenates them.

say 'ab' ~ 'c';     # abc

Junctive AND (all) Precedence

infix &

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

All junction operator.

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

Junctive OR (any) Precedence

infix |

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

Any junction operator.

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

infix ^

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

One junction operator.

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

Named Unary Precedence

prefix temp

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

"temporizes" the variable passed as the argument, which means it is reset to its old value on scope exit. (This is similar to the local operator in Perl 5, except that temp does not reset the value).

prefix let

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

Restores the previous value if the block exits unsuccessfully. A successful exit means the block returned a defined value or a list.

my $answer = 42;

{
    let $answer = 84;
    die if not Bool.pick;
    CATCH {
        default { say "it's been reset :(" }
    }
    say "we made it 84 sticks!";
}

say $answer;

In the above case, if the Bool.pick returns true, the answer will stay as 84 because the block returns a defined value (say returns true). Otherwise the die statement will cause the block to exit unsuccessfully, resetting the answer to 42.

Nonchaining Binary Precedence

infix does

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

Mixes $role into $obj at run time. Requires $obj to be mutable.

$role doesn't need to a be a role, it can be something that knows how to act like a role, for example enum values.

infix but

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

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

$role doesn't need to a be a role, it can be something that knows how to act like a role, for example enum values.

infix cmp

proto sub infix:<cmp>(Any, Any) returns Order:D is assoc<non>
multi sub infix:<cmp>(Any,       Any)
multi sub infix:<cmp>(Real:D,    Real:D)
multi sub infix:<cmp>(Str:D,     Str:D)
multi sub 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);      # Less
say 4        cmp 4.0;           # Same
say 'b'      cmp 'a';           # More

infix leg

proto sub infix:<leg>($a, $b) returns Order:D is assoc<non>
multi sub infix:<leg>(Any,   Any)
multi sub 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';        Less
say 'a' leg 'a';        Same
say 'b' leg 'a';        More

infix <=>

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

Numeric three-way comparator.

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

infix ..

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

Range operator

Constructs a Range from the arguments.

infix ..^

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

Right-open range operator.

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

infix ^..

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

Left-open range operator.

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

infix ^..^

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

Open range operator

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

Chaining Binary Precedence

infix ==

proto sub infix:<==>($, $) returns Bool:D is assoc:<chain>
multi sub infix:<==>(Any, Any)
multi sub infix:<==>(Int:D, Int:D)
multi sub infix:<==>(Num:D, Num:D)
multi sub infix:<==>(Rational:D, Rational:D)
multi sub infix:<==>(Real:D, Real:D)
multi sub infix:<==>(Complex:D, Complex:D)
multi sub infix:<==>(Numeric:D, Numeric:D)

Numeric equality operator.

Coerces both arguments to Numeric if necessary, and returns True if they are equal.

infix !=

proto sub infix:<!=>(Mu, Mu) returns Bool:D is assoc<chain>

Numeric inequality operator.

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

infix <

proto sub infix:«<»(Any, Any) returns Bool:D is assoc<chain>
multi sub infix:«<»(Int:D, Int:D)
multi sub infix:«<»(Num:D, Num:D)
multi sub infix:«<»(Real:D, Real:D)

Numeric less than operator.

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

infix <=

proto sub infix:«<=»(Any, Any) returns Bool:D is assoc<chain>
multi sub infix:«<=»(Int:D, Int:D)
multi sub infix:«<=»(Num:D, Num:D)
multi sub infix:«<=»(Real:D, Real:D)

Numeric less than or equal to operator.

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

infix >

proto sub infix:«>»(Any, Any) returns Bool:D is assoc<chain>
multi sub infix:«>»(Int:D, Int:D)
multi sub infix:«>»(Num:D, Num:D)
multi sub infix:«>»(Real:D, Real:D)

Numeric greater than operator.

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

infix >=

proto sub infix:«>=»(Any, Any) returns Bool:D is assoc<chain>
multi sub infix:«>=»(Int:D, Int:D)
multi sub infix:«>=»(Num:D, Num:D)
multi sub infix:«>=»(Real:D, Real:D)

Numeric less than or equal to operator.

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

infix eq

proto sub infix:<eq>(Any, Any) returns Bool:D is assoc<chain>
multi sub infix:<eq>(Any,   Any)
multi sub infix:<eq>(Str:D, Str:D)

String equality operator.

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

Mnemonic: equal

infix ne

proto sub infix:<ne>(Mu, Mu) returns Bool:D is assoc<chain>
multi sub infix:<ne>(Mu,    Mu)
multi sub infix:<ne>(Str:D, Str:D)

String inequality operator.

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

Mnemonic: not equal

infix gt

proto sub infix:<gt>(Mu, Mu) returns Bool:D is assoc<chain>
multi sub infix:<gt>(Mu,    Mu)
multi sub infix:<gt>(Str:D, Str:D)

String greater than operator.

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

Mnemonic: greater than

infix ge

proto sub infix:<ge>(Mu, Mu) returns Bool:D is assoc<chain>
multi sub infix:<ge>(Mu,    Mu)
multi sub infix:<ge>(Str:D, Str:D)

String greater than or equal to operator.

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

Mnemonic: greater or equal

infix lt

proto sub infix:<lt>(Mu, Mu) returns Bool:D is assoc<chain>
multi sub infix:<lt>(Mu,    Mu)
multi sub infix:<lt>(Str:D, Str:D)

String less than operator.

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

Mnemonic: less than

infix le

proto sub infix:<le>(Mu, Mu) returns Bool:D is assoc<chain>
multi sub infix:<le>(Mu,    Mu)
multi sub infix:<le>(Str:D, Str:D)

String less than or equal to operator.

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

Mnemonic: less or equal

infix before

proto sub infix:<before>(Any, Any) returns Bool:D is assoc<chain>
multi sub infix:<before>(Any,       Any)
multi sub infix:<before>(Real:D,    Real:D)
multi sub infix:<before>(Str:D,     Str:D)
multi sub 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

proto sub infix:<after>(Any, Any) returns Bool:D is assoc<chain>
multi sub infix:<after>(Any,       Any)
multi sub infix:<after>(Real:D,    Real:D)
multi sub infix:<after>(Str:D,     Str:D)
multi sub 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

proto sub infix:<eqv>(Any, Any) returns Bool:D is assoc<chain>
proto sub infix:<eqv>(Any, Any)

Equivalence operator. Returns True if the two arguments are structurally the same, i.e. from the same type and (recursively) contain the same values.

say [1, 2, 3] eqv [1, 2, 3];        # True
say Any eqv Any;                    # True
say 1 eqv 2;                        # False
say 1 eqv 1.0;                      # False

For arbitrary objects this is not possible with the default eqv operator. E.g., eqv will not 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);  #=> False

To get eqv semantics for objects of this class, one would need 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);  #=> True

infix ===

proto sub infix:<===>(Any, Any) returns Bool:D is assoc<chain>
proto sub infix:<===>(Any, Any)

Value identity operator. Returns True if both arguments are the same object.

my class A { };
my $a = A.new;
say $a === $a;              # True
say A.new === A.new;        # False
say A === A;                # True

For value types, === behaves like eqv:

say 'a' === 'a';            # True
say 'a' === 'b';            # False

# different types
say 1 === 1.0;              # False

=== uses the WHICH method to obtain the object identity, so all value types must override method WHICH.

infix =:=

proto sub infix:<=:=>(Mu \a, Mu \b) returns Bool:D is assoc<chain>
multi sub 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;      # False
$b = 2;
say $a;             # 1
$b := $a;
say $a =:= $b;      # True
$a = 5;
say $b;             # 5

infix ~~

The smart-match 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 an excerpt of built-in smart-matching functionality:

Right-hand side Comparison semantics
Mu:U type check
Str string equality
Numeric numeric equality
Regex regex match
Callable boolean result of invocation
Any:D object identity

infix =~=

proto sub infix:<=~=>($, $) returns Bool:D is assoc:<chain>
multi sub infix:<=~=>(Any, Any)
multi sub infix:<=~=>(Int:D, Int:D)
multi sub infix:<=~=>(Num:D, Num:D)
multi sub infix:<=~=>(Rational:D, Rational:D)
multi sub infix:<=~=>(Real:D, Real:D)
multi sub infix:<=~=>(Complex:D, Complex:D)
multi sub infix:<=~=>(Numeric:D, Numeric:D)

The approximately-equal operator. Calculates the relative 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. Note that this operator is not arithmetically symmetrical (doesn't do ± Δ):

my $x = 42;
say ($x + $*TOLERANCE) =~= $x;   # True
say ($x - $*TOLERANCE) =~= $x;   # False

The tolerance is supposed to be modifiable via an adverb:

    my ($x, $y) = 42, 42.1;
    say $x =~= $y :tolerance(.1);

however, this is not yet implemented. The same effect can be achieved by assigning to $*TOLERANCE.

{
    my $*TOLERANCE = .1;
    say 11 =~= 10;               # True
}

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

{
    my $*TOLERANCE = 0;
    say 1 =~= 1;                 # False
}

Tight AND Precedence

infix &&

Returns the first argument that evaluates to False in boolean context, or otherwise 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 of are never evaluated.

sub a { 1 }
sub b { 0 }
sub c { die "never called" };
say a() && b() && c();      # 0

Tight OR Precedence

infix ||

Returns the first argument that evaluates to True in boolean context, or otherwise the last argument.

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

sub a { 0 }
sub b { 1 }
sub c { die "never called" };
say a() || b() || c();      # 1

infix ^^

Returns the first true argument if there is only one, and Nil otherwise. Short-circuits as soon as two true arguments are found.

say 0 ^^ 42;                # 42
say 0 ^^ 42 ^^ 1 ^^ die 8;  # (empty line)

Note that the semantics of this operator may not be what you assume: infix ^^ flips to 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 //

Defined-or operator. Returns the first defined operand, or else the last operand. Short-circuits.

say Any // 0 // 42;         # 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

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

Conditional Operator Precedence

infix ?? !!

Ternary operator, conditional operator.

$condition ?? $true !! $false evaluates and returns the expression from the $true branch if $condition is a true value. Otherwise it evaluates and returns the $false branch.

infix ff

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

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/;  # prints only "AB"
}

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

for <A B C D E> {
    say $_ if /C/ ff *; # prints C, D, and 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 is 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 = <A B C>;
say $_ if /A/ ff /C/ for @list;  # prints A, B, and C
say $_ if /A/ ^ff /C/ for @list; # prints B and C

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

This operator cannot be overloaded, as it is 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 = <A B C>;
say $_ if /A/ ff /C/ for @list;  # prints A, B, and C
say $_ if /A/ ff^ /C/ for @list; # prints A and B

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

This operator cannot be overloaded, as it is 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 = <A B C>;
say $_ if /A/ ff /C/ for @list;  # prints A, B, and C
say $_ if /A/ ^ff^ /C/ for @list; # prints B

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

This operator cannot be overloaded, as it is 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 $_, and after that 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/;  # Prints "AB", "C", "D", and "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 is 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 = <A B C>;
say $_ if /A/ fff /C/ for @list;  # prints A, B, and C
say $_ if /A/ ^fff /C/ for @list; # prints B and C

For the non-sed version, see ^ff.

This operator cannot be overloaded, as it is 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 = <A B C>;
say $_ if /A/ fff /C/ for @list;  # prints A, B, and C
say $_ if /A/ fff^ /C/ for @list; # prints A and B

For the non-sed version, see ff^.

This operator cannot be overloaded, as it is 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 = <A B C>;
say $_ if /A/ fff /C/ for @list;  # prints A, B, and C
say $_ if /A/ ^fff^ /C/ for @list; # prints B

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

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

Item Assignment Precedence

infix =

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

Item assignment operator.

Places the value of the right-hand side into the container on the left-hand side. Its exact semantics are left to the container type on the left-hand side.

(Note that item assignment and list assignment have different precedence levels, and the syntax of the left-hand side decides whether an equal sign = is parsed as item assignment or list assignment operator).

infix =>

sub infix:«=>»($key, Mu $value) returns 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;         # a
say $p.value;       # 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 sub prefix:<not>(Mu $x) returns 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 sub prefix:<so>(Mu $x) returns Bool:D

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

Comma Operator Precedence

infix ,

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

Constructs a List from its arguments. 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 is a syntax error.

List Infix Precedence

infix Z

sub infix:<Z>(**@lists) returns List:D is assoc<chain>

Zip operator.

Interleaves the lists passed to Z like a zipper, stopping as soon as the first input list is exhausted:

say (1, 2 Z <a b c> Z <+ ->).perl;  #=> ((1, "a", "+"), (2, "b", "-")).Seq

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

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

infix X

sub infix:<X>(**@lists) returns List:D is assoc<chain>

Creates a cross product from all the lists, order so that the rightmost elements vary most rapidly:

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 meta operator, in which case the inner lists are replaced by the value from applying the meta'ed operator to the list:

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

infix ...

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

The sequence operator is a generic operator to produce lazy lists.

It can have initial elements and a generator on left-hand side, and an endpoint on the right-hand side.

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.

The default generator is *.succ or *.pred, depending on how the end points compare:

say 1 ... 4;        # 1 2 3 4
say 4 ... 1;        # 4 3 2 1
say 'a' ... 'e';    # a b c d e
say 'e' ... 'a';    # e d c b a

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

say (1 ... *)[^5];  # 1 2 3 4 5

Custom generators are the last argument before the '...' operator. This one takes two arguments, and generates the Fibonacci numbers

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

Of course the generator can also take only one argument.

say 5, { $_ * 2 } ... 40;                       # 5 10 20 40

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

Without a generator, and more than one initial element, and all initial elements numeric, the sequence operator tries to deduce the generator. It knows about arithmetic and geometric sequences.

say 2, 4, 6 ... 12;     # 2 4 6 8 10 12
say 1, 2, 4 ... 32;     # 1 2 4 8 16 32

If the endpoint is not *, it is smart-matched against each generated element, and the sequence is terminated when the smart-match succeeded. For the ... operator, the final element is included, for the ...^ operator it is excluded.

This allows you to write

say 1, 1, *+* ...^ *>= 100;

To generate all Fibonacci numbers up to but excluding 100.

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

my $end = 4;
say 1, 2, 4, 8, 16 ... $end;
# outputs 1 2 4

List Prefix Precedence

infix =

List assignment operator. Its exact semantics are left to the container type on the left-hand side. See Array and Hash for common cases.

The distinction between item assignment and list assignment is determined by the parser depending on the syntax of the left-hand side.

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.

infix ::=

Read-only binding operator. See infix :=.

listop ...

The yada, yada, yada operator or stub operator. If it is 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.

listop !!!

Fatal stub operator.

If it is 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 ???

Admonitory stub operator.

If it is 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

Loose AND precedence

infix and

Same as infix &&, except with looser precedence.

Returns the first operand that evaluates to False in boolean context, or otherwise the last operand, it short-circuits. Please note that and is easy to misuse, see traps.

infix andthen

Returns the first undefined argument, otherwise the last argument. 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 block or pointy block.

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

Same as infix //, except with looser precedence.

Returns the first defined argument, or else the last argument. Short-circuits.

Sequencer Precedence

infix ==>

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

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 is often required that you call with parentheses (though this is not required for the very last routine/method).

# 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 (left-to-right) with parentheses, read top-to-bottom
@result = (
    <people of earth>  # (1) Start with the input
    ==> map({ .tc })   # (2) Capitalize the words
    ==> grep /<[PE]>/  # (3) Look for P or E
    ==> sort           # (4) Sort, result is <Earth People>
);

# For illustration, method chaining equivalent, read top-to-bottom
@result =
    <people of earth>  # (1) Start with the input
    .map({ .tc })      # (2) Capitalize the words
    .grep(/<[PE]>/)    # (3) Look for P or E
    .sort;             # (4) Sort, result is <Earth People>

# To assign without the need of parentheses use another feed operator
<people of earth>
    ==> map({ .tc })
    ==> grep /<[PE]>/
    ==> sort()
    ==> @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 instead
    ==> grep /<[PE]>/
    ==> sort()
    ==> @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
@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
@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
@result
    <== sort()
    <== grep({ /<[PE]>/ })
    <== my @caps # unlike ==>, there is 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).