You are "sabotaging" one of the main use cases for the ternary conditional operator : to return an (l)value. ¹ ²

Better use if-then-else construct instead, if you don't want to take advantage, but execute complex code.

my $z; if ($x) {$z = "true\n"} else {$z = "false\n"}

But for my taste it's better written as

my $z = $x ? "true\n" : "false\n";

Your trap is even documented in perlop#Conditional-Operator

Because this operator produces an assignable result, using assignments without parentheses will get you in trouble. For example, this:

$x % 2 ? $x += 10 : $x += 2

Really means this:

(($x % 2) ? ($x += 10) : $x) += 2

Rather than this:

($x % 2) ? ($x += 10) : ($x += 2)

That should probably be written more simply as:

$x += ($x % 2) ? 10 : 2;

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

¹) See also WP : "The conditional operator's most common usage is to make a terse simple conditional assignment statement. "

²) tho I don't think I ever took advantage of the lvalue aspect, to create a LHS

DB<22> 1 ? $a : $b = 1 DB<23> x $a,$b 0 1 1 undef DB<24> 0 ? $a : $b = 2 DB<25> x $a,$b 0 1 1 2

(I'd certainly use parentheses in productive code.)


In reply to Re: Evaluating the condition ($x) (ternary conditional operator) by LanX
in thread Evaluating the condition ($x) by syphilis

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.