Forum Moderators: coopster & phranque

Message Too Old, No Replies

Printing the result of a ternary expression

         

csdude55

4:54 am on Aug 23, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Again, I'm out of practice... so please forgive me.

My script does some magic and then, if it succeeds, it defines $found; if it fails then it doesn't. It may also determine a value for $return... or it may not.

Then later, if $found is defined AND $return is defined, then I want to print $return. If $found is defined but $return is not, then I want to print "yes". And if $found is not defined, I want to print "no".

So this is what I have:

$found = true;

($found) ?
print $return //
print 'yes' :
print 'no';


Everything seems good, except that when $found is defined and $return is not, it prints "yes1" (not the trailing "1").

What tha deuce?

NickMNS

5:08 am on Aug 23, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



ternary expression returns a value and thus is not the same as an if statement.

ternary (pseudo code):
print $(found) ? 'yes' : 'no'

The expression returns the value to the print command, and the print command runs.

if statement (pseudo code):

if true:
print 'yes
else:
print 'no'

The if statement allows one block to run, and blocks the other.

Caveat, I don't know the details of Perl but I must assume that it is the same as others (JS)

csdude55

6:43 pm on Aug 23, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Interesting info, maybe... over 10,000 iterations, using Perl 5.22 via JDoodle.com:

# 0.0197887420654297
($found) ?
print $return //
print '1' :
print '0';
}

# 0.0209808349609375
if ($found) {
if ($return) { print $return; }
else { print '1'; }
}

else { print '0'; }

# 0.0288486480712891
$str = ($found) ?
$return //
'1' :
'0';

print $str;

# 0.0371932983398438
if ($found) {
if ($return) { $str = $return; }
else { $str = '1'; }
}

else { $str = '0'; }

print $str;


So using an if-else is marginally slower than a ternary, but the difference is so low as to be irrelevant.

I'm assuming that the ternary without setting it to a variable adds the "1" if the result is true, and then adds null if the result is false. If there's no way around that then I guess that the if-else has to be the best solution.