3

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?
yoniyes
  • 1,000
  • 11
  • 23
  • 2
    Related: http://stackoverflow.com/q/2630547/5830574 – PerlDuck Aug 09 '16 at 19:26
  • That answers my first question, thanks! It's also nice to know that `given` has more capabilities. – yoniyes Aug 09 '16 at 19:36
  • `given` used to set lexical `$_`, but that doesn't exist anymore. /// `given`'s expression is evaluated in scalar context, whereas `for` loops over the returned scalars. /// Something tells me there's a difference in the flow-control keywords allowed in `given` vs `for`. – ikegami Aug 09 '16 at 20:25

1 Answers1

7

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!

Community
  • 1
  • 1
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Great answer. Instinct told me `if-elsif-else` is slower than dedicated statements and modules for case handling, so if it's not slower at all, why even create these modules in the first place? – yoniyes Aug 09 '16 at 20:44
  • 2
    It's just syntax. For example, `given ($x) { when ([qw( a b c )]) { ... } when ([qw( d e f )]) { ... } ... }` vs `if (grep { $x eq $_ } qw( a b c )) { ... } elsif (grep { $x eq $_ } qw( d e f )) { ... } ...` – ikegami Aug 09 '16 at 20:46