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


In reply to Re: Code blocks with ternary operator or trailing conditionals by kcott
in thread Code blocks with ternary operator or trailing conditionals by puterboy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.