Search code examples
perlinheritancestrict

when using strict, perl can't find a child class method


I am having an issue when using strict in perl. I have a parent class called FlowStep and I have a child classes FlowStep_* which I want to inherit from FlowStep. FlowStep is loaded by perl immediately when I run. Depending on what flow step the user wishes to run, there is code to dynamically load the particular package for that step. For example, if the user runs "myFlowManager -step foo", the made flow manager code will run, determine the package for step foo, and load it.

So basically some code that says something like:

sub runPerlModule { 
   my $this        = shift;

   my $PMfullPath = $$this{"subPM"} ;               
   my $path   = dirname($PMfullPath);
   my $module = basename($PMfullPath, ".pm");

    # dynamically load the module
    push(@INC, $path);
    eval "require $module"; 
    # create a new object
    my $obj = $module->new();
    # call the child class's init code
    $obj->init();
    $obj->run();
}

One example flow step is called FlowStep_RunTiming. In FlowStep_RunTiming, I have the following:

use FlowStep;
use strict;

package FlowStep_RunTiming;
use base qw(FlowStep);   #i think this is the only command needed to setup inheritance

sub new {
 # some code to create
}
sub run {
# some code to run
}
1;

I am having a problem when using strict in FlowStep_RunTiming. If there are no syntax errors in FlowStep_RunTiming, there are no issues. If however there is a typo in FlowStep_RunTiming, then when I run the program, perl just complains that there is no run() method defined for FlowStep_RunTiming.

The package FlowStep_RunTiming is dynamically selected, so execution begins before perl can lint it. There must be a way though for perl to report the real issue, ie report the syntax error and line number with the error in FlowStep_RunTiming. Right now have to run, fail, and find the syntax error by eye.

Am I not setting up the child class correctly? Is there a way to make perl report the real syntax error and not give the "false" message that run() isn't defined. Anyone have any example of how to set this up correctly?

Thanks for your help.


Solution

  • Change eval "require $module"; to

    unless (eval "require $module") {
        die "Error in $module: $@";
    }
    

    Or do whatever else you want to when there's a typo.

    See perldoc perlvar and perldoc -f eval.