sulfericacid has asked for the wisdom of the Perl Monks concerning the following question:

Just read in a book about the ternary operator ? and have NO clue what it does or how to use it. I don't think my book describes to too well and I am way beyond confused. Can someone help me understand what it does, it's purpose, examples? It says it's like an if-then-else all in one *shrugs*. Any help would be greatly appreciated!



Replies are listed 'Best First'.
Re: ternary operator ?
by tommyw (Hermit) on Nov 29, 2002 at 10:38 UTC

    For a less esoteric example:

    $apples=3; $oranges=1; print "I have $apples ", $apples==1?"apple":"apples", "\n"; print "I have $oranges orange", $oranges==1?"":"s", "\n"; __END__ I have 3 apples I have 1 orange

    Too stupid to live.
    Too stubborn to die.

      Out of all the examples here, your's was definately the most understandable :) Thanks for trying to keep it basic and using something which would be a pretty practical use of it! I think I understand it more, thanks for your help!!

Re: ternary operator ?
by broquaint (Abbot) on Nov 29, 2002 at 10:31 UTC
    It's essentially like a returning inline if statement. The first expression is the test, and if it's true it will execute the expression after the question mark, if it's false, it will execute the expression after the colon e.g
    my $foo = "test"; print +( $foo =~ /^\w+\z/ ? "condition true" : "condition false" ),$/; my $bar = defined $x ? $x : "nought"; print "\$bar is: $bar", $/; __output__ condition true $bar is: nought
    See the Conditional Operator section in the perlop manpage for more details.


      I wouldn't say "execute", but rather "return". Why? Because it can also return lvalues. In ALGOL, one could do:
      IF a THEN b ELSE c FI := IF d THEN e ELSE f FI;

      which was great. You can do something like that in Perl using the ternary operator:

      ($a ? $b : $c) = ($d ? $e : $f);

      You can't do that in C or Java without use much more code.


        I wouldn't say "execute", but rather "return".
        So would I ;)
        It's essentially like a returning inline if statement.


Re: ternary operator ?
by fruiture (Curate) on Nov 29, 2002 at 10:34 UTC

    The ternary ?: is a short if-then-else:

    A ? B : C # is equivalent to if ( A ) { B } else { C }

    The advantage is that it's an expression, in contrast to if-else, which is a control structure. So.

    print A ? B : C; #correct # equivalent if-else? print if(A){ B }else{ C }; #nope # does the same, but doesn't mean the same: if( A ){ print B } else { print C }

    HTH. See perlop for further enlightment.

Re: ternary operator ?
by sulfericacid (Deacon) on Nov 29, 2002 at 11:21 UTC
    Thanks for your help everyone, I really appreciate it. In the book it really didn't say any of that, but it all makes sense now.

    Thanks again!

      Isn't it time you got yourself a better book?