It is true that the trinary operator can be used as an lvalue. On the other hand, I can't think of a legitimate reason why one would want to do so (although I'm open to suggestions).

As a first approximation, I think the expression is better written as

if( $flag ) { $on = $value; } else { $off = $value; }

Then again, the repeated assignments of the same value does look a little redundant. This could be recast as

${$flag ? \$on : \$off} = $value;

Which, not coincidentally, looks remarkably similar to the problem of pushing to the correct array, and to my twisted mind, seems a bit easier to follow than the initial code. The fact that the code looks weird alerts you to the fact that something weird is indeed going on.

But I digress. I posited that one should never use the ternary operator as an lvalue. When I see code that does this, it is usually a degenerate (in more ways than one) form of a hash. I would probably recast the two scalars as keys of a hash, which would give something like:

$status{$flag ? 'on' : 'off'} = $value;

That, to me, looks the clearest of all.


In reply to Re: Trinary operator can't be used as first argument of push by grinder
in thread Ternary operator can't be used as first argument of push by davido

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.