First of all, i'd write:

print $var ? 'yes' : 'no'

btw. it's a 'ternary' operator. I cannot agree with your results, my perl (5.6.1 and 5.8.0) lets ?: be only about 13% faster:

use Benchmark qw/cmpthese/; our @values = (1,0,undef,50,'yes','no','0E0',0e0,0); my $subs = { ifelse => sub {foreach(@values){ my $x; if($_){$x = 'yes'} else {$x = 'no'} }}, trinary => sub {foreach(@values){ my $x; $x = $_ ? 'yes' : 'no' }}, }; $_->() for values %$subs; cmpthese( $ARGV[0] => $subs );

And to finally (not) answer your question: The ?: operator is much "lighter" than if-else, it is one expression without scope, whereas the if-block can have it's own lexicals. If you wanted to have the functionaltiy of if-else in a ?: construct, you'd have to use do BLOCK, which already slows down the whole thing...

UPDATE: Aristotle is of course right about the "ternary" operator.

--
http://fruiture.de

In reply to Re: if-else vs. tertiary effieciency? by fruiture
in thread if-else vs. tertiary effieciency? by Anonymous Monk

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.