in reply to Re: Re: No braces
in thread No braces

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.

Replies are listed 'Best First'.
Re^4: No braces
by hardburn (Abbot) on Feb 11, 2004 at 14:42 UTC

    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; }

        Damian's Switch.pm relies on source filtering, which means that unless it can parse Perl perfectly (ha ha!), you'll get bugs in portions of code that having nothing to do with switches just because you included use Switch; in your code. So it shouldn't be used in any practical code.

        One of the advantages of a C-style switch is that it gives you O(1) efficiency in going through the cases, whereas all Perl idioms for emulating it have a O(n) worst case (or all cases, if you don't include a last to break the switch. This was discussed at Re: Perl Idioms Explained: && and || "Short Circuit" operators.

        Note that neither Switch.pm nor Perl6 switches offer O(1) efficiency, since they can't be implemented using jump tables like C switches are. For that, you need to use a dispatch table using hashes holding references to subroutines (super search for "dispatch table" should give interesting results).

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

        Note: All code is untested, unless otherwise stated