【问题标题】:when using strict, perl can't find a child class method使用 strict 时,perl 找不到子类方法
【发布时间】:2016-05-21 17:05:25
【问题描述】:

在 perl 中使用 strict 时遇到问题。我有一个名为 FlowStep 的父类,我有一个要从 FlowStep 继承的子类 FlowStep_*。当我运行时,FlowStep 会立即由 perl 加载。根据用户希望运行的流程步骤,有一些代码可以动态加载该步骤的特定包。例如,如果用户运行“myFlowManager -step foo”,则生成的流管理器代码将运行,确定步骤 foo 的包,并加载它。

所以基本上是一些类似这样的代码:

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();
}

一个示例流程步骤称为 FlowStep_RunTiming。在 FlowStep_RunTiming 中,我有以下内容:

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;

在 FlowStep_RunTiming 中使用 strict 时遇到问题。如果 FlowStep_RunTiming 中没有语法错误,则没有问题。但是,如果 FlowStep_RunTiming 中有错字,那么当我运行程序时,perl 只会抱怨没有为 FlowStep_RunTiming 定义 run() 方法。

包 FlowStep_RunTiming 是动态选择的,因此在 perl 可以 lint 之前开始执行。 perl 必须有一种方法可以报告真正的问题,即在 FlowStep_RunTiming 中报告语法错误和行号错误。现在必须运行,失败,并通过肉眼找到语法错​​误。

我没有正确设置子类吗?有没有办法让 perl 报告真正的语法错误,而不是给出未定义 run() 的“错误”消息。任何人都有如何正确设置的示例?

感谢您的帮助。

【问题讨论】:

  • 显示实际加载 FlowStep_RunTiming 的代码
  • @ysth 我刚刚为 FlowStep_RunTiming 的加载和运行添加了上面的代码

标签: perl inheritance strict


【解决方案1】:

eval "require $module";更改为

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

或者在出现拼写错误时做任何你想做的事情。

请参阅 perldoc perlvarperldoc -f eval

【讨论】:

  • 这只会导致 perl 死掉。我如何让它在死前打印拼写错误和行号?
  • 通过 eval 存储在 $@ 中
  • 感谢您的解决方案和解释……它奏效了!感谢您的帮助!
【解决方案2】:

在孩子身上我这样做;服务是父perl

use Service;
our @ISA= qw( Service );
sub new 
{
    my ($class, $args) = @_;
    my $self = $class->SUPER::new($args );
    bless $self, $class;
    return $self;
}

sub prerun{             #something calling run
    my ($self) = @_;
    $self->run();       #self becomes the first argument to run 
}

你需要将类/对象传递给每个函数

在父母中;

sub run
{
    my ($self) =  @_;
}

然后从孩子那里

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多