28

The conditional (ternary) operator suggests the ternary operator is a substitute for if ... else. I always thought so, but recently I have a logical problem with that.

Consider this short debug session:

  DB<1> $s='X'

  DB<2>  1 ? $s .= '_' : $s = '_'

  DB<3> x $s
0  '_'

So if 1 is true, then the expression $s .= '_' should be evaluated (and not $s = '_').

But why is $s just '_' at the end?

4
  • 4
    Only use the ternary operator for conditional expressions. Don't use it to select between statements; that makes for hard to read code and is generally asking for trouble. Use regular if/else for statements.
    – marcelm
    Sep 8, 2021 at 10:22
  • 3
    See the ternary operator as a tool for rvalue selection, not for branching.
    – Wolf
    Sep 8, 2021 at 13:50
  • If you read the link in the question saying "One way to reduce the verbosity of Perl code is to replace if-else statements with a conditional operator expression. The conditional operator (aka ternary operator) takes the form: logical test ? value if true : value if false." you might get the wrong idea ;-)
    – U. Windl
    Sep 8, 2021 at 13:54
  • FWIW, this is different in C++: int a = 87; 1 ? a += 1 : a = 1; will set a to 88, not to 1. In plain C it doesn't matter, as that combination is always an error. Unfortunately, it's common for "C-like" languages to get the ?: operator wrong, perl and php being too egregious examples.
    – user10678532
    Sep 10, 2021 at 20:15

3 Answers 3

47

The ternary conditional operator (?:) has a higher precedence than the assignment operator (=) (the table of the precedence of Perl's operator can be found in the Operator Precedence and Associativity section of perlop). As such, the line

1 ? $s .= '_' : $s = '_'

is parsed by Perl as

(1 ? ($s .= '_') : $s) = '_'

(You can check that by yourself by running perl -MO=Deparse <your program>)

Note also that $s .= '_' returns $s with the added _ at the end, and that this $s can be assigned to (in technical terms, it's an lvalue). This is documented in the Assignment Operators section of perlop:

Unlike in C, the scalar assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to.

So, basically, your code is doing

($s .= '_') = '_';

Which is equivalent to

$s .= '_';
$s = '_';
1
  • 2
    It makes sense usually you use the ternary operator for assigning the result, not assigning in the "branches". So the precedence of operators is fine for that case, but in my case using assignments in the branches I would have needed parentheses. My fault.
    – U. Windl
    Sep 8, 2021 at 6:10
18

It is an issue of operator precedence.

$ perl -MO=Deparse,-p -e '   
> $s='X';
> $t=1;
> $t ? $s .= '_' : $s = '_';
> print $s'
($s = 'X');
($t = 1);
(($t ? ($s .= '_') : $s) = '_');
print($s);
-e syntax OK

Whether the ternary condition is true or false, ultimately $s is set to "_".

To do what you intend to do, you need to add at least one set of parentheses:

1 ? $s .= '_' : ($s = '_');
15

The conditional operator only evaluates what's necessary, but you have a precedence problem.


First of all, the conditional operator is indeed guaranteed to use short-circuit evaluation, meaning it only evaluates what's necessary.

$ perl -M5.010 -e'
   sub f { say "f" }
   sub g { say "g" }
   $ARGV[0] ? f() : g();
' 0
f

$ perl -M5.010 -e'
   sub f { say "f" }
   sub g { say "g" }
   say $ARGV[0] ? f() : g();
' 1
g

This is even true for E1 || E2, E1 or E2, E1 && E2 and E1 and E2. They only evaluate their right-hand side operand if necessary.

$ perl -M5.010 -e'
   sub f { say "f"; $ARGV[0] }
   sub g { say "g"; $ARGV[1] }
   say f() || g();
' 3 4
f
3

$ perl -M5.010 -e'
   sub f { say "f"; $ARGV[0] }
   sub g { say "g"; $ARGV[1] }
   say f() || g();
' 0 4
f
g
4

This is why you can can evaluate open(...) or die(...) safely. Without short-circuiting, it would evaluate die whether open was successful or not.


Now, let's explain the following:

$s = "X";   1 ? $s .= "_" : $s = "_";         say $s;   # _

It's a precedence problem. The above is equivalent to

$s = "X";   ( 1 ? ($s .= "_") : $s ) = "_";   say $s;   # _

$s .= "_" returns $s, so the conditional operator returns $s, so the string _ is assigned to $s. If we add parens to get the desired parsing, we get the expected result.

$s = "X";   1 ? ($s .= "_") : ($s = "_");     say $s;   # X_

Alternative:

$s = "X";   $s = ( 1 ? $s : "" ) . "_";       say $s;   # X_
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.