There is an implementation in CPAN, but I don't think it's what we're looking for. It's certainly not straightforward, and dispatch tables are easy enough to roll your own.
You put a string in, you get a code ref out. Then, presumably, you execute the code ref:my %disp_table = ( something => \&do_something );
What could be simpler?$disp_table{'something'}->();
Now if the hash lookup returns nothing, you fall back on a subroutine that doesn't do anything. Of course, you could use a default that did something if you wanted to.($disp_table{'not there'} || sub {})->();
which should then raise a red flag that you need to abstract it out into its own subroutine. And if 'one' is supposed to do something before falling through, you can embed that sub call in its custom action:one => sub { print "Number!\n" }, two => sub { print "Number!\n" }, three => sub { print "Number!\n" },
By chaining calls this way, you can make things "fall through" to whatever you want them to. They are not limited by what comes next (which is good, because in a hash, what comes next is unpredictable).one => sub { print "The loneliest "; number() }, two => \&number, three => \&number,
Ranges offer a similar challenge. Of course, neither patterns nor ranges are handled by C's switch statement. Modula handles ranges, but it sacrifices fall-through (and may only work on numbers and single characters). You can't have everything. If you can't enumerate all the cases you want to cover, you don't want a dispatch table. Functions that check all the alternatives in order (such as my smatch) can offer a great deal of flexibility.
I have implemented a function that does the translation for all the features described above (except patterns and ranges, for the reasons cited) in the Snippet Switch/case as a dispatch table with C-style fall-through.
Update: I have written a module, Case, that implements dispatch tables (as well as a more complex smart-matching construct).
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Implementing Dispatch Tables
by deMize (Monk) on Jul 31, 2012 at 13:41 UTC | |
by jdporter (Paladin) on Jul 31, 2012 at 13:44 UTC | |
Re: Implementing Dispatch Tables
by Anonymous Monk on Jan 10, 2012 at 19:33 UTC |