in reply to What does the ternary statement actually do?

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. :-)

Replies are listed 'Best First'.
Re: Re: What does the ternary statement actually do?
by ichimunki (Priest) on Aug 10, 2001 at 21:17 UTC
    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.