Fri, 17 Oct 2008

Changes to Perl 5 Operators


Permanent link

NAME

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

SYNOPSIS

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

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

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

    # ternary, conditional op
    $a == $b ?? 2 * $a !! $b - $a

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

DESCRIPTION

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

Since |, ^ and & now construct junctions, the bit wise 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.IO ~~ :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/perl-5-to-6/11-basic-operators.trackback

xiaoyafeng wrote


It might be '/etc/passwd/' to me.

Jonathan Rynd wrote


You wrote "6 +^ 3 # 6" but that isn't even syntactically correct. I think you meant to write 6 +^ 3; # 5

Jonathan Rynd wrote


Also you wrote "Comparison operators can now be changed," when you meant "chained" (you got it right the second time)

Write a comment

The comments on this blog post have been disabled; the comment form below will not work.

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