It acts like C's ternary operator.

If you don't know C, here's a little more explanation. :-) It evaluates a condition, and then returns one of two alternatives. You could think of it like an if(...){...}else{...} that looks funny. Some examples:

sub doIfTrue() { print "Doing true stuff...\n" } sub doIfFalse() { print "Doing false stuff...\n" } my $booleanVariable = false; $booleanVariable ? doIfTrue() : doIfFalse();

The if..else equivalent would be written as:

if ( $booleanVariable == true ) { doIfTrue() } else { doIfFalse() }

or:

if ( $booleanVariable ) { doIfTrue() } else { doIfFalse() }

That's one way to use it, but you can also do some cooler things with it (cooler in the sense that it's shorter, a little mind-bending, etc.):

... my $daysRemaining = someFunction(); print "You have $daysRemaining ", $daysRemaining > 1 ? "days" : "day", " left to finish project X.\n";

If $daysRemaining computes to 2, you will "You have 2 days left to finish project X." On the other hand, if $daysRemaining computes to 1, your output will be "You have 1 day left to finish project X."

I asked a related question once (while posing as Anynomous Monk, or maybe that was before I got an account...I don't rememember).

Update: Man, you guys are fast (or I am long winded)...in the time it took me to reply, there were three or four other responses alread in. :-)


In reply to Re: What does the ternary statement actually do? by t'mo
in thread What does the ternary statement actually do? by Mr.T

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.