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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Easy dispatch tables. (pointless?)
by Aristotle (Chancellor) on Apr 02, 2003 at 22:38 UTC | |
by jryan (Vicar) on Apr 03, 2003 at 01:20 UTC | |
by Aristotle (Chancellor) on Apr 03, 2003 at 02:54 UTC | |
by jryan (Vicar) on Apr 03, 2003 at 06:57 UTC | |
by Aristotle (Chancellor) on Apr 03, 2003 at 08:25 UTC | |
| |
|
Re: Easy dispatch tables.
by hardburn (Abbot) on Apr 02, 2003 at 15:09 UTC | |
by jdporter (Paladin) on Apr 02, 2003 at 18:08 UTC | |
by hardburn (Abbot) on Apr 03, 2003 at 04:15 UTC |