in reply to Simple Switch statement

A switch statement is basically a dispatch table. I would use something like that. Other options would include something like:
for ($val) { /^1$/ && do { do_something }; /^abc$/ && do { do_something_else }; /^\d{2,4}$/ && do { do_something_further }; }

This is straight out of the Camel.

------
We are the carpenters and bricklayers of the Information Age.

The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Replies are listed 'Best First'.
Re: Re: Simple Switch statement
by bradcathey (Prior) on Sep 13, 2003 at 01:28 UTC
    I normally do just as dragonchild suggests, which is indeed right out of holy writ. However, don't be too quick to give up the old if/then/else. While maybe not as clean looking or as cool, the venerable standby can be about 2x as fast, though, admittedly, usually not noticeable unless you are testing thousands of conditions :-)

    Switch/case is one of the RARE features I miss from traditionally frowned upon javascript.
      I agree with what bradcathey said about if/then/else. Also on testing of simple strings/values. The mundane
      if ($a eq "simple value") { ... }
      runs faster than
      if ($a =~ /^simple value$/) { ... }
      The point is to avoid using regular expressions on simple string testing. Any bit of speed increase in perl is good, especially when it has to be evaluated countless times.

        Ah, but why not:

        for($switch_me) { /bob/ && do { print "Got 'bob'!\n"; break }; /frnak/ && do { print "Got 'frnak'!\n"; break }; $_ == 1 && do { print "Got 1!\n"; break }; print "Got nuttin'!\n"; }

        You can have your cake AND eat it too.

        Alakaboo