amiribarksdale has asked for the wisdom of the Perl Monks concerning the following question:

This question is really simple.

How do I export a dispatch table from an external module?

my $typecolors = { 1 => \&release, 2 => \&event, 3 => \&gossip, 4 => \&props, 5 => \&diss, 6 => \&other, }; sub release {...} sub event {...} sub gossip {...} sub props {...} sub diss {...} sub other {...}

I have tried

use subs qw($typecolors);

and it just doesn't work. $typecolors is OK to export in the module, and so are the subs it calls.

Amiri

Replies are listed 'Best First'.
Re: Exporting a Dispatch Table
by FunkyMonk (Bishop) on Apr 08, 2008 at 21:30 UTC
    I'd leave the dispatch table in your module and export a function that uses it:
    BEGIN { package DT; $INC{"DT.pm"} = 1; use strict; use warnings; use Exporter qw/import/; our @EXPORT_OK = qw{ dispatcher }; my $typecolors = { 1 => \&release, 2 => \&event, 3 => \&gossip, 4 => \&props, 5 => \&diss, 6 => \&other, }; sub dispatcher { my ( $verb, @args ) = @_; $typecolors->{$verb}->( @args ) } sub release { print "release\n" } sub event { print "event\n" } sub gossip { print "gossip\n" } sub props { print "props\n" } sub diss { print "diss\n" } sub other { print "other\n" } } package main; use strict; use warnings; use DT qw/dispatcher/; dispatcher( 2 ); # prints "event\n"

    Note that I've written this all in one file. If you're doing this properly, you don't need the BEGIN block that wraps DT, nor $INC{"DT.pm"} = 1.

      Aw, man. Of course. Thanks, FunkyMonk. Just making a function use a dispatch table, inside the subroutine, was of course the right answer. Much obliged.

      Amiri

Re: Exporting a Dispatch Table
by kyle (Abbot) on Apr 08, 2008 at 21:12 UTC

    You can export $typecolors like any other variable and use the referenced subs anywhere it lands. Use Exporter for this.

    I wonder, though, if you're asking about getting a dispatch table from a module that doesn't already export it. Since $typecolors is a lexical variable, this won't be possible. You'll have to get the module that owns the variable to hand it over to you.

      Not quite. It would need to be a package (our) variable instead of a lexical (my) variable for Exporter to see it.
Re: Exporting a Dispatch Table
by spx2 (Deacon) on Apr 08, 2008 at 21:58 UTC
    read this
    I find it to be a good source of knowledge and I go to it from time to time.
    It explains how to export/import whatever you need.