in reply to Ternary operators: a hinderance, not a help

This is an old thread, but I can't believe nobody used this kind of example:
$statement_type = $hate_ternary ? "if (condition) {} else {}" : $love_ternary ? 'var = condition ? valuetrue : condition2 ? valuefalsetrue : valuefalse' : 'keep = it ? simple : stupid';

Here are my personal guidelines:
Rule 1 - keep ternary operations simple
Rule 2 - use the best format or method
Rule 3 - if you really have to combine tenaries, it's better to daisychain them than to nest them (hint - complicate the False term, not the True term)

Combining ternaries
Not OK:
my $value = $condition1 ? ($condition2 ? $value1 : $value2) : $value3;
OK for some programmers:
my $value = $condition1 ? $value1 : $condition2 ? $value2 : $value3;

That last example is equivalent to a basic if, elsif, else. This should only be done for basic and simple tasks.

  • Comment on Re: Ternary operators: a hinderance, not a help

Replies are listed 'Best First'.
Re^2: Ternary operators: a hinderance, not a help
by stevieb (Canon) on Mar 14, 2018 at 21:32 UTC

    Personally, I only use ternary ops (which I do use frequently) if it is as basic as it gets:

    return $x ? $y : $z;

    If there is more than one condition, it's if/elsif/else, and if it gets much beyond that, I use a hash/dispatch table or some form of hash mechanism to just "drop-in" the result of the condition to present the result I want.