Fri, 17 Oct 2008

Changes to Perl 5 Operators


Permanent link

NAME

"Perl 5 to 6" Lesson 11 - Changes to Perl 5 Operators

SYNOPSIS

    # bitwise operators
    5   +| 3;       # 7
    5   +^ 3;       # 6
    5   +& 3;       # 1
    "b" ~| "d";     # 'f'
 
    # string concatenation
    'a' ~ 'b';      # 'ab'

    # file tests
    if '/etc/passwd'.path ~~ :e { say "exists" }

    # repetition
    'a' x 3;        # 'aaa'
    'a' xx 3;       # 'a', 'a', 'a'

    # ternary, conditional op
    my ($a, $b) = 2, 2;
    say $a == $b ?? 2 * $a !! $b - $a;

    # chained comparisons
    my $angle = 1.41;
    if 0 <= $angle < 2 * pi { ... }

DESCRIPTION

All the numeric operators (+, -, /, *, **, %) remain unchanged.

Since |, ^ and & now construct junctions, the bitwise operators have a changed syntax. They now contain a context prefix, so for example +| is bit wise OR with numeric context, and ~^ is one's complement on a string. Bit shift operators changed in the same way.

String concatenation is now ~, the dot . is used for method calls.

File tests are now formulated in Pair notation, Perl 5 -e is now :e. If something other than $_ should be used as the file name, it can be supplied via $filename.path ~~ :e.

The repetition operator x is now split into two operators: x replicates strings, xx lists.

The ternary operator, formerly $condition ? $true : $false, is now spelled $condition ?? $true !! $false.

Comparison operators can now be chained, so you can write $a < $b < $c and it does what you mean.

MOTIVATION

Many changes to the operators aim at a better Huffman coding, ie give often used things short names (like . for method calls) and seldom used operators a longer name (like ~& for string bit-wise AND).

The chaining comparison operators are another step towards making the language more natural, and allowing things that are commonly used in mathematical notation.

SEE ALSO

http://perlcabal.org/syn/S03.html#Changes_to_Perl_5_operators

[/perl-5-to-6] Permanent link

Comments / Trackbacks:

Trackback URL: /blog-en.trackback

Write a comment

 
Name:
URL: [http://www.example.com/] (optional)
Title: (optional)
Comments:
Save my Name and URL/Email for next time