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 |