in reply to Avoiding if/else knots

The Switch and Switch-Perlish modules both give you nice syntactic constructs for just such situations. There's a FAQ on this:
How do I create a switch or case statement?

We're building the house of the future together.

Replies are listed 'Best First'.
Re^2: Avoiding if/else knots
by exussum0 (Vicar) on Aug 18, 2006 at 21:21 UTC
    switches are awesome for simple short cases. hashes for complex ones. pick yer poison. :)

      I could say the reverse as well. Hash-based dispatch tables have a significant limitation: they're hash based. That means any condition you look up by has to be a hash key, which means it (or its stringification) has to exist in the hash. Of course, you can increase your flexibility in this area by using some of the funky TIEHASH modules available on CPAN, such as Tie-Hash-Approx, Tie-Hash-KeysMask, Tie-Hash-Regex, and Tie-RangeHash. But in the general case, I believe switches are more powerful because (at least in the typical Perl implementations) there are no limitations on the conditions. Switches also give you defaults, which can be hard to do with hashes without the aid of special tie modules, and fallthrough, which is even harder. Try writing this using a dispatch table:

      use Switch::Perlish; switch $var, sub { case sub { $_[0] > 9 }, sub { warn "$var>9"; fallthrough }; case 9, \&found_it; default \&not_found; };
      We're building the house of the future together.