in reply to elseif syntax error

I find it helps clean up code a lot to use early exits. Consider using:

sub someSub { if (some condition) { ... return; } if (some other condition) { ... return; } }

instead of:

sub someSub { if (some condition) { ... } elsif (some other condition) { ... } }

Despite taking a few more lines the first version makes it much clearer what the conditions are for some task to be performed and makes the exit conditions much clearer. This technique can often collapse deeply nested conditional code to a single level.

The same technique can be applied in loops to take early leave of the current iteration (using next) or terminate the loop early (using last).


True laziness is hard work

Replies are listed 'Best First'.
Re^2: elseif syntax error
by schetchik (Beadle) on Oct 28, 2009 at 12:53 UTC
    But if you use multiple if both blocks can be executed, and in case of using "elsif" construction only one block is executed. Or not? :)

      Look again. Not if you use an early exit at the end of each block.

      The whole point of the technique is to use an early exit at the end of each block to avoid the need to nest blocks and allow else blocks to turn into a simple unindented block of code.


      True laziness is hard work