Camelia

Operators

src

Operator Precedence

In an expression like 1 + 2 * 3 , the 2 * 3 is evaluated first because the infix * has tighter B<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 I<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 routine; postcircumfix operators as methods, all others as subroutines. 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 the I<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 L<#prefix ...> etc. stub operators. (Niecza currently turns postcircumfix operators in a subroutine call, while Rakudo interprets them as methods).

Term Precedence

circumfix < >

The quote-words construct. Breaks up the contents on whitespace, and returns a Parcel of the words. If a word looks like a number literal or a Pair literal, it is converted the appropriate number.
    say <a b c>[1];     # b

 
(Rakudo currently always returns a parcel of strings).

circumfix ( )

The grouping operator. An empty group () creates an empty L<Parcel>. 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

 

circumfix { }

Block or L<Hash> constructor. If the contents looks like a list of pairs and does not use L<$_> or other placeholder parameters, returns an itemized L<Hash>. Otherwise it contructs a L<Block>. Note that this construct does not reparse 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 L<Hash>.

circumfix [ ]

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

Method Postfix Precedence

postcircumfix { }

The hash indexing postcircumfix. Fail on type L<Any>, and on L<EnumMap>, L<Hash> and related types it allows lookup of hash elements by key.
    my %h = a => 1, b => 2;
    say %h{'a'};        # 1
    say %h{'a', 'b'};   # 1, 2

 

postcircumfix < >

The hash indexing quote-words operator. Interprets the argument list as a list of words, just like < circumfix < >>, and then calls < postcircumfix:<{ } >>, i.e. the hash indexing operator. Thus you can write
    my %h = a => 1, b => 2;
    say %h<a>;          # 1
    say %h<b a>;        # 2, 1

 

postcircumfix ( )

The call operator. Treats the invocant as a L<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 postcircumfix:<( ) >>.

postcircumfix [ ]

The array indexing operator. Treats the invocant as a L<Positional> and indexes it by position.
    my @a = 'a' .. 'z';
    say @a[0];                      # a

 
Lists of indexes produce list of results as if they were all indexed separetely.
    my @a = 'a' .. 'z';
    say @a[15, 4, 17, 11].join;     # perl

 
L<Callable> indexes are invoked with the number of elements as arguments. This lets you write
    my @a[*-1];                     # z

 
to index lists and arrays from the end. Non-L<Positional> invocants are interpreted as a one-list element of the object.

postfix .

The operator for calling one method, $invocant.method . Technically this is not an operator, but syntax special-cased in the compiler.

postfix .?

Potential method calls. $invocant.?method calls method method on $invocant if it has a method of such name. Otherwise it returns L<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 L<Parcel> 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 L<Parcel> of the results. If no such method was found, an empty L<Parcel> is returned. Technically this is not an operator, but syntax special-cased in the compiler. # TODO: .= .^ .:: .() .[] .{} .<>

Autoincrement Precedence

prefix ++

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

 
Increments its argument by one, and returns the incremented value.
    my $x = 3;
    say ++$x;       # 4
    say $x;         # 4

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

prefix --

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

 
Decrements its argument by one, and returns the decremented value.
    my $x = 3;
    say --$x;       # 2
    say $x;         # 2

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

postfix ++

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

 
Increments its argument by one, and returns the unincremented value.
    my $x = 3;
    say $++x;       # 3
    say $x;         # 4

 
It works by calling the L<succ> method (for I<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<none>

 
Decrements its argument by one, and returns the undecremented value.
    my $x = 3;
    say $x--;       # 3
    say $x;         # 2

 
It works by calling the L<pred> method (for I<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

 

Exponentation Precedence

infix **

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

 
The exponentiation operator coerces both arguments to L<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 (L<Int>, L<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 L<Bool> by calling the Bool method on it. Note that this collapses L<Junction>s.

prefix !

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

 
Negated boolean context operator. Coerces the argument to L<Bool> by calling the Bool method on it, and returns the negation of the result. Note that this collapses L<Junction>s.

prefix +

    multi sub prefix:<+>(Any) returns Numeric:D

 
Numeric context operator. Coerces the argument to L<Numeric> by calling the Numeric method on it.

prefix -

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

 
Negative numeric context operator. Coerces the argument to L<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 L<Str> by calling the Str method on it.

prefix |

Flattens objects of type L<Capture>, L<Enum>, L<Pair>, L<List>, L<Parcel>, L<EnumMap> and L<Hash> into an argument list. (In Rakudo, this is implemented not as a proper operator but as a special case in the compiler, which means it only works in argument lists, not in arbitrary code).

prefix +^

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

 
Integer bitwise negation. Coerces the argument to L<Int> and does a bitwise negation on the result, assuming L<two's complement|https://en.wikipedia.org/wiki/Two%27s_complement>.

prefix ?^

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

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

prefix ^

    multi sub prefix:<^>(Any) returns Range:D

 
I<upto> operator. Coerces the argument to L<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

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

infix /

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

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

infix div

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

 
Integer division. Rounds down.

infix %

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

 
Modulo operator. Coerces to L<Numeric> first. Generally the following identity holds:
    $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 I<AND>. Coerces both arguments to L<Int> and does a bitwise I<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 L<Int> and returns the greatest common denominator.

infix lcm

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

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

Additive Precedence

infix +

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

 
Coerces both arguments to L<Numeric> and adds them.

infix -

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

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

infix +|

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

 
Coerces both arguments to L<Int> and does a bitwise I<OR> (inclusive OR) operation.

infix +^

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

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

infix ?|

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

 
Coerces both arguments to L<Bool> and does a logical I<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)

 
Coerces $a to L<Str> and $b to L<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

 
Returns a list of $a repeated and evaluated $b times ( $b is coerced to L<Int>). If < $b <= 0 >, the empty list is returned. The left-hand side is evaluated for each repetition, so
    [1, 2] xx 5

 
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)

 
Coerces both arguments to L<Str> and concatenates them.
    say 'ab' ~ 'c';     # abc

 

Junctive AND (all) Precedence

infix &

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

 
Creates an I<all> L<Junction> from its arguments. See L<Junction> for more details.

Junctive OR (any) Precedence

infix |

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

 
Creates an I<any> L<Junction> from its arguments. See L<Junction> for more details.

infix ^

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

 
Creates a I<one> L<Junction> from its arguments. See L<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 L<local|http://perldoc.perl.org/functions/local.html> operator in Perl 5, except that temp does not reset the value).

prefix let

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

 
Hypothetical reset: if the current scope is exited either through an exception or fail() , the old value is restored.

Nonchaining Binary Precedence

infix does

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

 
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<none>

 
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<none>
    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>(Enum:D,    Enum:D)
    multi sub infix:<cmp>(Version:D, Version:D)

 
Generic, "smart" three-way comparator. Compares strings with string semantics, numbers with number semantics, L<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);      # Increase
    say 4        cmp 4.0;           # Same
    say 'b'      cmp 'a';           # Decrease

 

infix leg

    proto sub infix:<leg>($a, $b) returns Order:D is assoc<none>
    multi sub infix:<leg>(Any,   Any)
    multi sub infix:<leg>(Str:D, Str:D)

 
String three-way comparator. Coerces both arguments to L<Str>, and then does a lexicographic comparison.

infix <=>

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

 
Numeric three-way comparator. Coerces both arguments to L<Real>, and then does a numeric comparison.

infix ..

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

 
Constructs a L<Range> from the arguments.

infix ..^

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

 
Constructs a L<Range> from the arguments, excluding the end point.

infix ^..

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

 
Constructs a L<Range> from the arguments, excluding the start point.

infix ^..^

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

 
Constructs a L<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)

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

infix !=

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

 
Coerces both arguments to L<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)

 
Coerces both arguments to L<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)

 
Coerces both arguments to L<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)

 
Coerces both arguments to L<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)

 
Coerces both arguments to L<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)

 
Coerces both arguments to L<Str> (if necessary), and returns True if both are equal. Mnemonic: I<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)

 
Coerces both arguments to L<Str> (if necessary), and returns False if both are equal. Mnemonic: I<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)

 
Coerces both arguments to L<Str> (if necessary), and returns True if the first is larger than the second, as determined by lexicographic comparison. Mnemonic: I<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)

 
Coerces both arguments to L<Str> (if necessary), and returns True if the first is equal to or larger than the second, as determined by lexicographic comparison. Mnemonic: I<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)

 
Coerces both arguments to L<Str> (if necessary), and returns True if the first is smaller than the second, as determined by lexicographic comparison. Mnemonic: I<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)

 
Coerces both arguments to L<Str> (if necessary), and returns True if the first is equal to or smaller than the second, as determined by lexicographic comparison. Mnemonic: I<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>(Enum:D,    Enum:D)
    multi sub infix:<before>(Version:D, Version:D)

 
Generic ordering, uses the same semantics as L<cmp|#infix 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>(Enum:D,    Enum:D)
    multi sub infix:<after>(Version:D, Version:D)

 
Generic ordering, uses the same semantics as L<cmp|#infix 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.

infix ===

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

 
Value identity. Returns True if both arguments are the same object.
    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 L<WHICH> method to obtain the object identity, so all value types must override method WHICH .

infix =:=

    proto sub infix:<=:=>(Mu $a is rw, Mu $b is rw) returns Bool:D is assoc<chain>
    multi sub infix:<=:=>(Mu $a is rw, Mu $b is rw)

 
Container identity. Returns L<True> if both arguments are bound to the same container.

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


 

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 L<Nil> otherwise. Short-circuits as soon as two true arguments are found.
    say 0 ^^ 42;                # 42
    say 0 ^^ 42 ^^ 1 ^^ die 8;  # (empty line)

 

infix //

Defined-or operator. Returns the first defined operand. Short-circuits.
    say Any // 0 // 42;         # 0

 

infix min

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

infix max

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

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. # TODO: ff, ^ff, ff^, ^ff^, fff, ^fff, fff^, ^fff^

Item Assignment Precedence

infix =

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

 
Item assignment. Places the value of the left-hand side into the container on the right-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

 
L<Pair> constructor. Constructs a L<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 L<Pair> within an argument list with an unquoted identifier on the left is interpreted as a named argument.

Loose Unary Precedence

prefix not

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

 
Evaluates its argument in boolean context (and thus collapses L<Junction>s), and negates the result.

prefix so

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

 
Evaluates its argument in boolean context (and thus collapses L<Junction>s), and returns the result.

Comma Operator Precedence

infix ,

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

 
Constructs a L<Parcel> 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", "-")).list

 
The Z operator also exists as a meta operator, in which case the inner parcels 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> 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 parcels are replaced by the value from applying the meta'ed operator to the list:
    1..3 X~ <a b> 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 *. L<succ> or *. L<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 * (L<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.

List Prefix Precedence

item = (list assignment)

List assignment. Its exact semantics are left to the container type on the left-hand side. See L<Array> and L<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.

listop ...

The I<yada, yada, yada> operator or I<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 L<&fail>, with the default message stub code executed .

listop !!!

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 L<&die>, with the default message stub code executed .

listop ???

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 L<&warn>, with the default message stub code executed .

Loose AND precedence

infix and

Same as L<#infix &&>, except with looser precedence. Returns the first operand that evaluates to False in boolean context, or otherwise the last operand. Short-circuits.

infix andthen

Returns the first undefined argument, otherwise the last argument. Short-circuits.

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. Short-circuits.

infix orelse

Same as infix // , except with looser precedence. Returns the first defined argument, or else the last argument. Short-circuits.

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.
Email:
Name: