Name

Yet Another Perl 6 Operator: The Conditional Operator

Version

Maintainer: Adriano Ferreira <ferreira@cpan.org>
Date: 17 Dec 2007
Last Modified: 18 Dec 2007
Number: 11
Version: 2
Status: Draft

Body

The syntax of an if-then-else expression in Perl 6 is composed by the conditional operator.

say "My answer is: ", $maybe ?? 'yes' !! 'no';

The expression above is equivalent to that, which uses the if-then-else statement within a do.

say "My answer is: ", do {
    if $maybe {
        'yes';
    } 
    else {
        'no';
    }
};

The operator '?? !!' syntactically breaks the expression into three subexpresssions. The first is evaluated in boolean context and, based on that result, one of the two parts are evaluated. (It never evaluates both of them.) If the conditional is true, it evaluates and returns the middle part; if false, the right part.

The choice for the strong markers '??' and '!!' was done to enhance the visibility of the construction. Contrast this to the typical C expression (which Perl 5 also adopted):

$maybe ? 'yes' : 'no'

where the tokens '?' and ':' easily blend with other symbols in complex expressions, making harder to distinguish what's going on without extra spaces and layout.

To stop some common errors, it is a syntax error to use an operator with looser precedence (such as '=') in the middle part.

my $x;
hmm() ??  $x = 1  !!  $x = 2;      # ERROR
hmm() ?? ($x = 1) !! ($x = 2);     # works

Be aware that both sides have to be parenthesized. A partial fix is even wronger:

hmm() ?? ($x = 1) !!  $x = 2;      # parses, but WRONG

which actually means

(
  hmm() ?? ($x = 1) !! $x
) = 2;

always assigning 2 to $x (because ($x = 1) is a valid lvalue).

Also to help catch errors by programmers used to C-derived languages (like Perl 5 itself), the Perl 6 parser will produce an error when a bare question mark is seen in infix position and suggest that ?? !! should be used instead. That is an example of pseudo operators that will be introduced to catch migratory brainos at compile time, helping the transition into the new language and common first-time mistakes by the would-be Perl 6 programmers. A non-exhaustive list of such operators is postfix:{'->'} , infix<?> , and infix:<=~> .

Note. That article is a mere rewriting of the section on "Conditional operator precedence" from Synopsis 03 .

$Revision: 94 $