in reply to What does the ternary statement actually do?

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'

Replies are listed 'Best First'.
Re: (jeffa) Re: What does the ternary statement actually do?
by dmmiller2k (Chaplain) on Aug 13, 2001 at 23:01 UTC

    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)' => '.')