Reputation: 1030
In one of the last scripts I wrote, I needed a behavior similar to a switch statement behavior. A simple search of an equivalent in Perl led me to use Switch
. At the beginning, all was fine and working, until everything just crashed with errors that are not very descriptive (it happened on a switch statement that had cases with regex, but strangely it didn't happen on other switch statements that are alike).
EDIT: the code that crashed was looking like this one:
switch ($var) {
case /pattern1/ {...}
case /pattern2/ {...}
...
else {...}
}
That led me to abandon the use of Switch.pm
and search for an alternative.
I found given
and for-when
and of course there's always the straightforward and somewhat naive if-elsif-else
.
Switch.pm
so unstable?given
and for-when
have a similar structure, but I guess there's a difference (because both exist). What is it?if-elsif-else
significantly slower than the other options?Upvotes: 4
Views: 3310
Reputation: 386331
Perl's when
and smart-matching are experimental, and they won't become features without backward-incompatible changes. You should not use these.
Switch.pm is a source filter, so it can produce incorrect error message when something's wrong. It also suffers from the same problems as smart-matching. You should not use this.
So, of the options you listed, only one is viable, and it's not any slower at all!
Upvotes: 8