Dispatch tables are great and convienient, but sometimes can be a bit of a pain to write. You have references flying over here and closures flying over there; yuck! Thats much too complicated for so simple of an idea. Wouldn't it be great if you could say "Ok, I have a set of subs here, and I want a dispatch table that maps each subname to each sub... Go do it, Perl genie!" With this short snippet of a module, now you can. Just throw your subs in a module, use Dispatch;, and a create_dptable subroutine that (surpise!) creates a dispatch table that maps each subname in the package to its corresponding sub will magically appear to serve you.
Here's an example:
package TestPkg; use Dispatch; sub sub_a { # ... } sub sub_b { # ... } sub _sub_b_helper { # not part of the table! # ... } sub sub_c { print $_[0]; } package main; my $table = create_dptable TestPkg; # or TestPkg::create_dptable(); $table->{sub_c}->("Hello!");
Update: Added a feature such that subroutines whose names start with a _ do not become part of the dispatch table.
package Dispatch; sub import { my $pkg = (caller)[0]; *{"${pkg}::create_dptable"} = sub { my %dispatch; my @oksymbols = grep { !/^_/ && !/^create_dptable$/ && defined *{"${pkg}::$_"}{CODE} } keys %{*{"${pkg}::"}}; $dispatch{$_} = *{"${pkg}::$_"}{CODE} foreach ( @oksymbols ); return \%dispatch }; } 1;
In reply to Easy dispatch tables. by jryan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |