For simple conditions and small blocks of code, there's not too much wrong with an if/elsif cascade, except perhaps that if all your conditions are integers, especially a contiguous range of integers, it means that you are sometimes testing more conditions than necessary.
For small, contiguous ranges of conditions, I prefer a array-based dispatch table. This can also be coded inline, although having the condition at the end may be seen as a disadvantage:
( sub{ $abc == 1 }, sub{ $def == 1 }, sub{ $xyz == 1 }, )[ $x - 1 ]->();
Somewhat obfuscate, but quite clear and efficient for small contiguous ranges. The absence of a simple 'default' mechanism is a shame.
For discontiguous ranges, a similar arrangment using an anonymous hash can work
${{ 1 => sub{ $abc == 1 }, 3 => sub{ $def == 1 }, 5 => sub{ $xyz == 1 }, }}{ $x }->();
The biggest problem, besides the obscurity of the construction, is the absence of a simple 'default' mechanism.
Of course they don't have to be inline, and can used a named array or hash, which also gives the possibility for providing for a default.
In reply to Re: Use of SWITCH vs IF ELSE in speed and readability
by BrowserUk
in thread Use of SWITCH vs IF ELSE in speed and readability
by bradcathey
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |