in reply to Conditional Elimination

Put the conditions in a sub. Then you can test things piece-wise with multiple ifs. Arrange them so that the first if will most likely return a fail. This makes the sub decide early and speeds up the code.

sub some_test {
  my ( $a, $b, $p, $s ) = @_;

  return 0 if $a ne 'A';
  return 0 if $b ne 'C';
  ...
}

Replies are listed 'Best First'.
Re^2: Conditional Elimination
by JavaFan (Canon) on Aug 30, 2011 at 20:00 UTC
    Your speed argument doesn't make any sense. Really, you think calling a sub and hand rolling your own short circuiting beats the build in short circuiting of && and ||?

      No, I think using a sub makes it easier to read. Making those tests that will return early will not slow it down as much as putting them in random order. It's just something to keep in mind when writing the sub. But the most important thing is to put the condition in a sub so that it's easier to understand.

        I'd say that correctness is far more important than speed when it comes to assigning order.
        But the most important thing is to put the condition in a sub so that it's easier to understand.
        How does that magic work? You're still have the same tests. Personally, I find:
        if (bunch of clauses) { code }
        easier to understand then
        if (pointer-where-to-find-clauses) { code }
        specially when it comes to better understanding of the clauses.