=NAME Yet Another S Operator: The Conditional Operator =VERSION Maintainer: Adriano Ferreira Date: 17 Dec 2007 Last Modified: 18 Dec 2007 Number: 11 Version: 2 Status: Draft =head1 Body The syntax of an if-then-else expression in S 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 C. say "My answer is: ", do { if $maybe { 'yes'; } else { 'no'; } }; The operator C<'?? !!'> 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 C<'??'> and C<'!!'> was done to enhance the visibility of the construction. Contrast this to the typical C expression (which S also adopted): $maybe ? 'yes' : 'no' where the tokens C<'?'> and C<':'> 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 C<'='>) 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 C<2> to C<$x> (because C<($x = 1)> is a valid lvalue). Also to help catch errors by programmers used to C-derived languages (like S itself), the S parser will produce an error when a bare question mark is seen in infix position and suggest that C 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 S programmers. A non-exhaustive list of such operators is C<< postfix:{'->'} >>, C<< infix >>, and C<< infix:<=~> >>. I That article is a mere rewriting of L< the section on "Conditional operator precedence" from Synopsis 03 | http://perlcabal.org/syn/S03.html#Conditional_operator_precedence >. $Revision: 94 $ =begin comment Keywords: Perl Perl 6 operators ternary operator trinary operator conditional operator =end comment