Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Ternary operators: a hinderance, not a help

by BitDreamer (Sexton)
on Mar 14, 2018 at 18:51 UTC ( [id://1210904]=note: print w/replies, xml ) Need Help??


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.

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1210904]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2024-03-28 23:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found