Is it possible to call a subroutine in the main package from a Perl module? I want to implement a dispatch table in the module, but have been trying for two days to figure out how to call the subroutine by reference (and I even tried calling it with a name in a variable).

package ProcessData; use strict; no strict "refs"; use Carp qw(croak); sub new { my ($pkg) = $_[0]; bless { _dispatch_table => {}, }, $pkg; } sub add_subroutine { if($_[1] && $_[2]) { if(ref($_[2]) eq "CODE") { ${$_[0]->{_dispatch_table}}{$_[1]} = $_[2]; } else { croak "The reference passed to add_subroutine() is not a C +ODE reference. "; } } else { croak "Insufficient arguments passed to add_subroutine(). "; } } sub process_data { if($_[1] && $_[2]) { #I've tried: ${$_[0]->{_dispatch_table}}{$_[1]}->($_[2]); #and tried ${${$_[0]->{_dispatch_table}}{$_[1]}}->($_[2]); #and some pretty odd other comibnations ... do stuff with the data ... } else { croak "Insufficient arguments passed to process_data(). "; } } sub process_locations { $_[0]->process_data("locations"); } test.pl use strict; use ProcessData; my $pd = ProcessData->new(); #Add references to the dispatch table. $pd->add_subroutine("dates", \&get_dates); $pd->add_subroutine("locations" \&get_locations); $pd->add_subroutine("contact_list", \&contact_list); $pd->process_locations;

This is a simplified code example, I'm trying to lean how to do this with a dispatch table. It's not something real ... yet... which is good ... because I haven't been able to Goolge an answer yet.


In reply to Is it possible to call a package::main subroutine from a module? by TorontoJim

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.