I stayed away from ternary for a long time, but once you get use to it, it is a nice tool to have. It is certainly not a choice of either ternary or if, keep both in your tool box and you will be happy. I use ternary when they are simple cases like your example. It is ofter the most usefull for defaulting values and not creating several lines of if constructs. It is also usefull if you want to embed different things in a string.

print "You have $items " . ($items == 1 ? "object." : "objects.");

Certianly not the most poetic use of it, but it should demonstrate the use well enough. If you find your self using temporary variable and if structures, it might just be that you can use a tenrary to replace them. Now in that same example if i wanted to say "object(s)" more than once you can break it out int a single ternary:

my $objects = $items == 1 ? "object" : "objects"; print "You have $items $objects. What would you like to do with your $ +objects?";

And then if you I am going to change multiple variable based on the state of one, use an if. These are just my rules, guidlines, expereinces. Keep all your tools handy and sharp, because most things in perl fit somewhere, honest, they weren't just thrown in for the heck of it. Like any tool, if used wrong, they can do more damage than good. ;)


___________
Eric Hodges

In reply to Re: Ternary operators: a hinderance, not a help by eric256
in thread Ternary operators: a hinderance, not a help by Tanalis

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.