Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

What does the ternary statement actually do?

by Mr.T (Sexton)
on Aug 10, 2001 at 19:35 UTC ( #103910=perlquestion: print w/replies, xml ) Need Help??
Mr.T has asked for the wisdom of the Perl Monks concerning the following question:

Hello everyone!
I had a question after reading some of the perl man pages that contain " : ? " (the ternary statement) and I can't figure out how it actually works, even after reviewing the information from the man page!

Could anyone explain it to me in simple terms?

qw/"I pity da foo' who don't use Perl!"/;
  • Comment on What does the ternary statement actually do?

Replies are listed 'Best First'.
(jeffa) Re: What does the ternary statement actually do?
by jeffa (Bishop) on Aug 10, 2001 at 19:38 UTC
    It is simply a quick and dirty if-else statement:
    return $is_true ? 'is true!' : 'is false'; # is just a one line way of saying if ($is_true) { return 'is true!'; } else { return 'is false!'; }

    Let me elaborate a bit more (aka update):
    You can even nest them:

    $a = $is_true ? 'is true!' : $was_true ? 'was true' : 'was never true' +;
    $a will contain one of the strings depending upon the value of $is_true and $was_true.

    The 'hook' operator (as i like to call it) is best used for assignments, as my examples showed. Don't be tempted to do this, as it is just bad coding practice:

    $some_boolean ? do_sub1() : do_sub2();


    perl -le '$x="jeff";$x++ for(0..4482550);print $x'

      At the risk of beating a dead horse:

      The ternary expression is an expression, whereas the if equivalent is a statement.

      In even more other words, the if statement cannot be used as a component of an expression while the ternary operator can.

      So, this:

      my $x = $is_true ? 'is true!' : 'is false';

      may be considered a shorter way of saying this (note that the my $x; must appear outside of the if):

      my $x; if ($is_true) { $x = 'is true!'; } else { $x = 'is false!'; }

      But, one cannot always simply condense an arbitrary if statement into a ternary expression

      -----[ BofA: 212 583-8077 David.Miller(AT)bofasecurities(DOT)com ]-----
      David M. Miller                       | phone/FAX:         212 662-0715
      Business Visions, Inc., Suite #8E     | cell:              917 952-1600
      680 West End Ave, New York, NY  10025 | e-mail: dmmiller(AT)acm(DOT)org
            Spam Resistant (replace '(AT)' => '@', and '(DOT)' => '.')
Re: What does the ternary statement actually do?
by davorg (Chancellor) on Aug 10, 2001 at 19:44 UTC

    In simple terms, it works like an if statement. The ternary operator has three parts (hence the name!) that look like this:

    condition ? expression1 : expression2

    The condition is evaluated. If it it true then expression1 is returned, otherwise expression2 is returned. Here's a simple example:

    $max = $x > $y ? $x : $y;

    The condition $x > $y is evaluated. If this is true then the operator returns $x, otherwise it returns $y. This could also be done using if like this:

    if ($x > $y) { $max = $x; } else { $max = $y; }

    But in this case I think that the ternary operator looks more readable.


    Perl Training in the UK <>

Re: What does the ternary statement actually do?
by t'mo (Pilgrim) on Aug 10, 2001 at 19:56 UTC

    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() }


    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) the time it took me to reply, there were three or four other responses alread in. :-)

      Don't worry t'mo! Your answer was very complete and well worth the extra effort. As you point out, the ternary operator is very useful anywhere you might put an expression. Which means you can do a 'my' with a ternary assignment, which means you can put it in a print statement's argument list, which means you can do return wantarray ? @list, $list[0]; at the end of your subs to check context and return appropriately... and all sorts of other useful stuff where an if-then is not only cumbersome, but completely unexpressive.
Re: What does the ternary statement actually do?
by bikeNomad (Priest) on Aug 10, 2001 at 19:40 UTC
    The ternary just allows an expression to have one of two values based on a test. That is:
    $a = 1 ? 'abc' : 'def'; # sets $a to 'abc' $a = 0 ? 'abc' : 'def'; # sets $a to 'def'
Re: What does the ternary statement actually do?
by Maclir (Curate) on Aug 10, 2001 at 21:21 UTC
    As well as the explanations given by the others above (that is, the ternary operator acts as shorthand for an if-then-else construct), it has a special perlish capability that you can assign to it.

    Actually, if the second and third arguments are valid "lvalues" (things what you can assign stuff to), then you can have the ternary expression on the left hand side of an assignment operation. For example, consider the following:

    ($cheque_account_sel ? $cheque_balance : $card_balance ) -= $payment;
    So based on a boolean flag ($cheque_account_sel) being true, the variable $cheque_balance is reduced by the value of $payment, otherwise the variable $card_balance is reduced by that amount.

    Why would you want to use that? I don't know, but it is there.

Re: What does the ternary statement actually do?
by dga (Hermit) on Aug 10, 2001 at 21:22 UTC

    Suitably described above. There is one handy case not mentioned as I begin to type this

    $bobscats=2; $billscats=1; printf "Bob has %s\n", catstat($bobscats); printf "Bill has %s\n", catstat($billscats); sub catstat { my($count)=@_; sprintf "%d %s", $count, $count>1?'cats':'cat'; }

    will print out Bob has 2 cats
    Bill has 1 cat
    So that it doesn't appear that you aren't sure how to say things like xxx has 1 cat(s)

      In C mode, that's what I usually do, only slightly different:
      printf ("%d %s%s\n", $count, "cat", ($count==1)?"":"s"); printf ("%d %s%s\n", $count, "cact", ($count==1)?"us":"i"); printf ("%d %s%s\n", $count, "Elvi", ($count==1)?"s":"i");
      As an alternative, you might want to use:
      print $count, "cat", (($count==1)?"":"s"), "\n"; print $count, "cact", (($count==1)?"us":"i"), "\n"; print $count, "Elvi", (($count==1)?"s":"i"), "\n";
      Or perhaps as a method:
      sub quantize { my ($quantity, $singular, $plural) = @_; return (1==$quantity)? $singular : $plural; } $count = 2; print "$count @{[quantize($count,'cat','cats')]}\n";

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://103910]
Approved by root
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (10)
As of 2018-07-19 15:58 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (411 votes). Check out past polls.