People who wish to use the ternary inline- conditional operator (? :
) for choosing to execute between two different statements with side-effects instead of using if
and else
. For example:
# Bad code cond_var ? (hash["if_true"] += "Cond var is true") : (hash["if_false"] += "Cond var is false")
(This is assuming the ternary operator was indeed written correctly, which is not always the case).
However, the ternary operator is meant to be an expression that is a choice between two values and should not be used for its side-effects. To do the latter, just use if
and else
:
if (cond_var) { hash["if_true"] += "Cond var is true"; } else { hash["if_false"] += "Cond var is false"; }
This is safer, and better conveys one’s intentions.
For more information, refer to a relevant thread on the Perl beginners mailing list (just make sure you read it in its entirety).