in reply to Re^2: conditional print. Is correct to use it?
in thread conditional print. Is correct to use it?
"if(true){a} else {b}" or just (a||b)
(are both equally correct?)
A statement block like if(true){a} else {b} does not evaluate to any value (but see Note 1 below), but an expression like (a||b) always does. Therefore, IMHO it's not correct to say these are equivalent or "equally correct." The if/else-statement block can be made to have an effect equivalent to the expression, but only if the a b expressions or statement(s) have the correct side effects.
An expression can always be incorporated into another expression — if precedence is handled properly! A statement cannot be incorporated into another statement unless you contort your program logic with some sort of usually unnecessary eval nonsense. E.g.:
Win8 Strawberry 5.8.9.5 (32) Wed 10/28/2020 15:06:58 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings my $x; # undefined/false my $y = 'default string'; my $side; if (not $x) { $side = $y; } # true clause has side effect # $side = $y unless $x; # a more terse alternative printf "side effect '%s' logical-or '%s' ternary '%s' \n", $side, ($x || $y), $x ? $x : $y; ^Z side effect 'default string' logical-or 'default string' ternary 'de +fault string'
Notes:
the return value of bar() is returned by func() if $x is true, that of fie() if $x is false.sub func { ... ... if ($x) { foo(); bar(); } else { fee(); fie(); } }
Win8 Strawberry 5.8.9.5 (32) Wed 10/28/2020 22:49:24 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings printf "'%s' returned from true clause \n", func(1); printf "'%s' returned from false clause \n", func(); sub func { my $x = shift; printf "x is %-7s", $x ? 'true' : 'false'; if ($x) { foo(); bar(); } else { fee(); fie(); } } sub foo { return 'from ' . (caller 0)[3]; } sub bar { return 'from ' . (caller 0)[3]; } sub fee { return 'from ' . (caller 0)[3]; } sub fie { return 'from ' . (caller 0)[3]; } ^Z x is true 'from main::bar' returned from true clause x is false 'from main::fie' returned from false clause
Give a man a fish: <%-{-{-{-<
|
|---|