in reply to Re: Avoiding if/else knots
in thread Avoiding if/else knots

switches are awesome for simple short cases. hashes for complex ones. pick yer poison. :)

Replies are listed 'Best First'.
Re^3: Avoiding if/else knots
by jdporter (Paladin) on Aug 20, 2006 at 12:19 UTC

    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.