In a batch-export script at at work, we constantly modify sites to which we need to export data. Each site has different needs, parameters, etc. To solve the problem, we created different .pl files that get 'require()'d, and functions called dynamically in the &$sub_name manner. The problem is if one script (that gets require()d) has a type-o, it will cause the full batch-post script to fail. Here was my solution; hope this is useful to anyone needing to call dynamic functions that are changed in multiple files by multiple people frequently.
my $PREFIX = '/home/xpost-scripts'; my %xscripts = ( site_a => 'a_funct', site_b => 'b_funct' ); foreach (keys(%xscripts)) { if (!system("perl -cw $PREFIX/$_")) { # perl -cw exits with '0' if +no errors. require ("$PREFIX/$_"); } else { print STDERR "Warning: File $_ had errors!\n"; } } # ... Here, we grabbed the Function name from a DB query. It's a hash +for this example. foreach (keys(%xscripts)) { if (defined($xscripts{$_})) { &$xscripts{$_}("A parameter"); } else { print STDERR "Error. Could not call function $xscripts{$_}\n"; } }
  • Comment on Dynamically loading perl files (and calling dynamic functions) with error checking.
  • Download Code

Replies are listed 'Best First'.
(bbfu) (eval) Re: Dynamically loading perl files (and calling dynamic functions) with error checking.
by bbfu (Curate) on Jun 07, 2001 at 07:46 UTC

    Have you thought about using eval for error checking on the require? So your code would become something like:

    my $PREFIX = '/home/xpost-scripts'; my %xscripts = ( site_a => 'a_funct', site_b => 'b_funct' ); foreach (keys(%xscripts)) { eval { require ("$PREFIX/$_") }; print STDERR "Warning: File $_ had errors: '$@'\n" if($@); } # ... Here, we grabbed the Function name from a DB query. It's a hash +for this example. foreach (keys(%xscripts)) { if (defined($xscripts{$_}) && ref($xscripts{$_}) && UNIVERSIAL::isa( +$xscripts{$_}, 'CODE')) { &$xscripts{$_}("A parameter"); } else { print STDERR "Error. Could not call function $xscripts{$_}\n"; } }

    Don't know if this would work 100% for your needs but it's a thought.

    bbfu
    Seasons don't fear The Reaper.
    Nor do the wind, the sun, and the rain.
    We can be like they are.