yonyon100 yonyon100 - 1 year ago 91
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
and search for an alternative.

I found
and of course there's always the straightforward and somewhat naive

  1. Why is
    so unstable?

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

  3. Is
    significantly slower than the other options?

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download