This page was generated at 2008-05-17 02:01:10 GMT.
(syn r14541, pugs-tests r20436, pugs-smoke r19912)
  [ Index of Synopses ]

TITLE

Synopsis 3: Perl 6 Operators

AUTHOR

Luke Palmer <luke@luqui.org>

VERSION

  Maintainer: Larry Wall <larry@wall.org>
  Date: 8 Mar 2004
  Last Modified: 2 Apr 2008
  Number: 3
  Version: 135

Overview

For a summary of the changes from Perl 5, see "Changes to Perl 5 operators".

Operator precedence

From t/operators/precedence/builtins.t lines 12–186 (46 √, 2 ×): (skip)

 

Not counting terms and terminators, Perl 6 has 23 operator precedence levels (same as Perl 5, but differently arranged). Here we list the levels from "tightest" to "loosest", along with a few examples of each level:

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

The associativities specified above are:

        Assoc     Meaning of $a op $b op $c
        =====     =========================
    L   left      ($a op $b) op $c
    R   right     $a op ($b op $c)
    N   non       ILLEGAL
    C   chain     ($a op $b) and ($b op $c)
    X   list      op($a, $b, $c) or op($a; $b; $c)

Note that list associativity only works between identical operators. If two different list-associative operators have the same precedence, they are assumed to be left-associative with respect to each other. For example, the X cross operator and the Z zip operator both have a precedence of "list infix", but:

    @a X @b Z @c

is parsed as:

    (@a X @b) Z @c

If you don't see your favorite operator above, the following sections cover all the operators in precedence order. Basic operator descriptions are here; special topics are covered afterwards.

Term precedence

This isn't really a precedence level, but it's in here because no operator can have tighter precedence than a term. See S02 for longer descriptions of various terms. Here are some examples.

Method postfix precedence

All method postfixes start with a dot, though the dot is optional for subscripts. Since these are the tightest standard operator, you can often think of a series of method calls as a single term that merely expresses a complicated name.

See S12 for more discussion of single dispatch method calls.

Autoincrement precedence

From t/spec/S03-operators/autoincrement.t lines 9–51 (30 √, 0 ×): (skip)

 

From t/operators/auto.t lines 9–98 (38 √, 5 ×): (skip)

 

From t/operators/inc.t lines 7–142 (39 √, 0 ×): (skip)

 

As in C, these operators increment or decrement the object in question either before or after the value is taken from the object, depending on whether it is put before or after. Also as in C, multiple references to a single mutating object in the same expression may result in undefined behavior unless some explicit sequencing operator is interposed. See "Sequence points".

As with all postfix operators in Perl 6, no space is allowed between a term and its postfix. See S02 for why, and for how to work around the restriction with an "unspace".

As mutating methods, all these operators dispatch to the type of the operand and return a result of the same type, but they are legal on value types only if the (immutable) value is stored in a mutable container. However, a bare undefined value (in a suitable Scalar container) is allowed to mutate itself into an Int in order to support the common idiom:

    say $x unless %seen{$x}++;

Increment of a Str (in a suitable container) works similarly to Perl 5, but is generalized slightly. A scan is made for the final alphanumeric sequence in the string that is not preceded by a '.' character. Unlike in Perl 5, this alphanumeric sequence need not be anchored to the beginning of the string, nor does it need to begin with an alphabetic character; the final sequence in the string matching <!after '.'> <rangechar>+ is incremented regardless of what comes before it.

From t/spec/S03-operators/autoincrement.t lines 52–111 (8 √, 4 ×): (skip)

 

The <rangechar> character class is defined as that subset of \w that Perl knows how to increment within a range, as defined below.

The additional matching behaviors provide two useful benefits: for its typical use of incrementing a filename, you don't have to worry about the path name or the extension:

    $file = "/tmp/pix000.jpg";
    $file++;            # /tmp/pix001.jpg, not /tmp/pix000.jph

Perhaps more to the point, if you happen to increment a string that ends with a decimal number, it's likely to do the right thing:

    $num = "123.456";
    $num++;             # 124.456, not 123.457

Character positions are incremented within their natural range for any Unicode range that is deemed to represent the digits 0..9 or that is deemed to be a complete cyclical alphabet for (one case of) a (Unicode) script. Only scripts that represent their alphabet in codepoints that form a cycle independent of other alphabets may be so used. (This specification defers to the users of such a script for determining the proper cycle of letters.) We arbitrarily define the ASCII alphabet not to intersect with other scripts that make use of characters in that range, but alphabets that intersperse ASCII letters are not allowed.

If the current character in a string position is the final character in such a range, it wraps to the first character of the range and sends a "carry" to the position left of it, and that position is then incremented in its own range. If and only if the leftmost position is exhausted in its range, an additional character of the same range is inserted to hold the carry in the same fashion as Perl 5, so incrementing '(zz99)' turns into '(aaa00)' and incrementing '(99zz)' turns into '(100aa)'.

The following Unicode ranges are some of the possible rangechar ranges. For alphabets we might have ranges like:

    A..Z        # ASCII uc
    a..z        # ASCII lc
    Α..Ω        # Greek uc
    α..ω        # Greek lc (presumably skipping U+03C2, final sigma)
    א..ת        # Hebrew
      etc.      # (XXX out of my depth here)

For digits we have ranges like:

    0..9        # ASCII
    ٠..٩        # Arabic-Indic
    ०..९        # Devangari
    ০..৯        # Bengali 
    ੦..੯        # Gurmukhi
    ૦..૯        # Gujarati
    ୦..୯        # Oriya
      etc.

Other non-script 0..9 ranges may also be incremented, such as

    ⁰..⁹        # superscripts (note, cycle includes latin-1 chars)
    ₀..₉        # subscripts
    0..9      # fullwith digits

Conjecturally, any common sequence may be treated as a cycle even if it does not represent 0..9:

    Ⅰ..Ⅻ        # clock roman numerals uc
    ⅰ..ⅻ        # clock roman numerals lc
    ①..⑳        # circled digits 1..20
    ⒜..⒵        # parenthesize lc
    ⚀..⚅        # die faces 1..6
    ❶..❿        # dingbat negative circled 1..10
      etc.

While it doesn't really make sense to "carry" such numbers when they reach the end of their cycle, treating such values as incrementable may be convenient for writing outlines and similar numbered bullet items. (Note that we can't just increment unrecognized characters, because we have to locate the string's final sequence of rangechars before knowing which portion of the string to increment. Note also that all character increments can be handled by lookup in a single table of successors since we've defined our ranges not to include overlapping cycles.)

Perl 6 also supports Str decrement with similar semantics, simply by running the cycles the other direction. However, leftmost characters are never removed, and the decrement fails when you reach a string like "aaa" or "000".

Increment and decrement on non-<Str> types are defined in terms of the .succ and .pred methods on the type of object in the Scalar container. More specifically,

    ++$var
    --$var

are equivalent to

    $var.=succ
    $var.=pred

If the type does not support these methods, the corresponding increment or decrement operation will fail. (The optimizer is allowed to assume that the ordinary increment and decrement operations on integers will not be overridden.)

Increment of a Bool (in a suitable container) turns it true. Decrement turns it false regardless of how many times it was previously incremented. This is useful if your %seen array is actually a KeySet, in which case decrement actually deletes it from the KeySet.

Exponentiation precedence

Symbolic unary precedence

Multiplicative precedence

Any bit shift operator may be turned into a rotate operator with the :rotate adverb. If :rotate is specified, the concept of sign extension is meaningless, and you may not specify a :signed adverb.

Additive precedence

Replication

Concatenation

From t/operators/operator.t lines 17–19 (1 √, 0 ×): (skip)

 

From t/operators/operator.t lines 49–53 (1 √, 0 ×): (skip)

 

Junctive and (all) precedence

Junctive or (any) precedence

Named unary precedence

Functions of one argument

    int
    sleep
    abs
    sin
    ...         # see S29 Functions

Note that, unlike in Perl 5, you must use the .meth forms to default to $_ in Perl 6.

There is no unary rand function in Perl 6, though there is a .rand method call and a 0-ary rand term.

Nonchaining binary precedence

Chaining binary precedence

From t/spec/S03-operators/equality.t lines 10–41 (15 √, 0 ×): (skip)

 

From t/spec/S03-operators/relational.t lines 9–49 (20 √, 0 ×): (skip)

 

All operators on this precedence level may be chained; see "Chained comparisons".