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

Hi, I have a main perl script that uses a bunch of generic modules. One module Generic_Funcs.pm is called by a bunch of different applications. I want to have inside a function within that module a call to a function within a totally separate module (i.e. PLCFuncs.pm a function called calcTot or PPDFuncs.pm called the same thing). How can I generically handle a function call to another module without saying it specifically such as PLCFuncs::calcTot()? Thanks. Rob

Replies are listed 'Best First'.
Re: Call external function
by Corion (Patriarch) on Sep 05, 2007 at 14:29 UTC

    From moritz's reply I think that your problem exposition wasn't entirely clear. My image of your situation is the following:

    #!/usr/bin/perl -w package PLCFuncs; sub calcTot { "The total is 10 PLCs" }; package PPDFuncs; sub calcTot { "The total is 42 PPDs" }; package Generic_Funcs; use strict; use Carp qw(croak); =head2 C<calc_totals KIND> Returns the calculated total. The kind is either C<PPD> or C<PLC>. =cut use vars qw(%calcTotals); %calcTotals = ( PLC => \&PLCFuncs::calcTot, PPD => \&PPDFuncs::calcTot, ); sub calculate_totals { my ($kind) = @_; croak "Unknown kind '$kind'" unless exists $calcTotals{ $kind }; my $calcTot = $calcTotals{$kind}; $calcTot->(); }; package main; use strict; for my $kind (qw(PPD PLC)) { print "Totals for $kind\n"; print Generic_Funcs::calculate_totals($kind), "\n" };

    If you want to pass arbitrary callbacks around, just use references to subroutines:

    sub get_and_print_totals { my ($callback) = @_; my $res = $callback->(); print "The total is >$res<\n"; }; get_and_print_totals( sub { return "hello total world" }); get_and_print_totals( sub { return 42+10 });
Re: Call external function
by moritz (Cardinal) on Sep 05, 2007 at 14:19 UTC
    If the external module supports that, you can import the function:

    use PLCFuncs qw/calcTot/;