in reply to Re: No braces
in thread No braces

I like the ternary also instead of using braces. Less noise.

But to help me make sense of the statement when I (or someone else) look at it later on, I use multiple lines as in:

$x = $x == 7 ? 8 : 0;

Thus, if you don't speak fluent "precedence", this structure does all the work. (Even bordering on "it's right when it's beautiful"?)

Replies are listed 'Best First'.
Re: Re: Re: No braces
by flyingmoose (Priest) on Feb 11, 2004 at 13:56 UTC
    The greatest fear of that operator comes from chaining. It's deceptively cool looking to use, so occasionally folks will do something like this (C, Java, Perl, it doesn't matter....)
    $x = (y == z) ? (a == c) ? foo (a,c) : bar (y,c) : (a == b) ? baz (a,y) : zap (y,y);

    Identation helps, but there are still cases when a nested if-comb can be more readable.

      A big problem is that Perl doesn't have a proper switch statement, which means a chained ? : is used far more often that it otherwise would.

      ----
      : () { :|:& };:

      Note: All code is untested, unless otherwise stated

        Point taken. Looking over CPAN right now, it appears Damian wrote a Switch module. I really wish something like this was in the core distribution. Well, I guess we can wait a few years for Perl 6! Anyone have experience with this?

        See below. I have done something like this before and didn't like it much, but it got the job done. Really though, it's not any cleaner than the if-comb due to the extra semantic gorp.

        foo: { if (/^abc/) { $abc = 1; last foo; } if (/^def/) { $def = 1; last foo; } if (/^xyz/) { $xyz = 1; last foo; } $nothing = 1; }