TorontoJim has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Is it possible to call a package::main subroutine from a module?
by BrowserUk (Patriarch) on Mar 21, 2016 at 22:11 UTC | |
|
Re: Is it possible to call a package::main subroutine from a module?
by AnomalousMonk (Archbishop) on Mar 22, 2016 at 02:06 UTC | |
|
Re: Is it possible to call a package::main subroutine from a module?
by Anonymous Monk on Mar 21, 2016 at 22:42 UTC | |
by TorontoJim (Beadle) on Mar 21, 2016 at 23:05 UTC | |
by Anonymous Monk on Mar 21, 2016 at 23:12 UTC | |
by TorontoJim (Beadle) on Mar 22, 2016 at 16:25 UTC |