in reply to Use of SWITCH vs IF ELSE in speed and readability

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.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
If I understand your problem, I can solve it! Of course, the same can be said for you.