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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.