yonyon100 yonyon100 - 3 months ago 20
Perl Question

switch vs. given vs. for-when vs. if-elsif-else in Perl

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
.


  1. Why is
    Switch.pm
    so unstable?

  2. It seems
    given
    and
    for-when
    have a similar structure, but I guess there's a difference (because both exist). What is it?

  3. Is
    if-elsif-else
    significantly slower than the other options?


Answer

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!