http://qs1969.pair.com?node_id=1074094


in reply to Code blocks with ternary operator or trailing conditionals

G'day puterboy,

Trying to force multiple statements and conditions into one line of code does not necessarily result in "cleaner" code. You leave yourself open to all sorts of precedence and syntax issues.

Future maintenance can also become a headache: instead of simply adding "statement 3;" to a well laid out block of code, you may need to deal with bugs due to unforeseen precedence issues or you may need to rewrite that whole block because "statement 3;" introduces syntactical incompatibilities.

Code like:

if (condition) { statement 1; statement 2; } else { statement 3; statement 4; }

will almost certainly be more readable and maintainable than a syntactically correct version of:

condition ? {statement 1; statement 2} : {statement 3; statement 4}

Having said that, here's two ways that you might have written your first example:

$ perl -e 'print "hello\n" and print "bye\n" if 1' hello bye
$ perl -e 'print("hello\n"), print "bye\n" if 1' hello bye

Here's how you might have handled the ternary example (using my previous example you should be able to see a second way to do this):

$ perl -e '1 ? (print "hello\n" and print "bye\n") : (print "hello2\n" + and print "bye2\n")' hello bye

Had I needed to write code like this, I probably would have used do {...} blocks as shown by Athanasius (in fact, that was my first thought before scrolling down and seeing that solution).

You should also familiarise yourself with the precedence issues explained in the ternary operator documentation.

-- Ken