Perl不继承基本方法

3

我有一个模块,作为其他几个模块的基础:

package P::Hb2::BaseMetric;

use strict;
use warnings;

sub new {
    my $class = shift;
    my $self = bless {}, $class;
    $self->init(ref($_[0]) eq 'HASH' ? @_ : {@_});
    return $self;
}

sub init {
    my ($self, $args) = @_;
    foreach (keys %{$args}) {
        $self->{$_} = $args->{$_};
    }
    return $self;
} 

sub mark {
    die "Metric not implemented.";
}

1;

我尝试使用以下方式继承它:
package P::Hb2::CPUInfo;

use strict;
use warnings;
use P::Hb2Utils;
use base 'P::Hb2::BaseMetric';

sub mark {
    my $self = shift;
    my $time = `date +%s` * 1000;
    my $stats = (split /\n/, `iostat -c 1 2`)[-1];

    $stats =~ /(\s+)([0-9]+\.[0-9]+)(\s+)([0-9]+\.[0-9]+)(\s+)([0-9]+\.[0-9]+)(\s+)([0-9]+\.[0-9]+)(\s+)([0-9]+\.[0-9]+)(\s+)([0-9]+\.[0-9]+)/;
    my %nice = (name => 'sys.cpu.iostat.nice.percent', datapoints => [[$time, $4]], tags => {});
    my %idle = (name => 'sys.cpu.iostat.idle.percent', datapoints => [[$time, $12]], tags => {});
    my %steal = (name => 'sys.cpu.iostat.steal.percent', datapoints => [[$time, $10]], tags => {});
    my %user = (name => 'sys.cpu.iostat.user.percent', datapoints => [[$time, $2]], tags => {});
    my %iowait = (name => 'sys.cpu.iostat.iowait.percent', datapoints => [[$time, $8]], tags => {});
    my %system = (name => 'sys.cpu.iostat.system.percent', datapoints => [[$time, $6]], tags => {});
    my @metrics;

    push @metrics, \%nice;
    push @metrics, \%idle;
    push @metrics, \%steal;
    push @metrics, \%user;
    push @metrics, \%iowait;
    push @metrics, \%system;
    return \@metrics;
}

1;

并尝试使用以下代码进行调用:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

require P::Hb2::CPUInfo;

my $ref = P::Hb2::CPUInfo->new({hello => "world"});
my @metric = $ref->mark();

print Dumper($ref);
print Dumper(\@metric);

但是当我这样做时,会出现错误:
Can't locate object method "new" via package "P::Hb2::CPUInfo" at test.pl line 9.
1个回答

2

在任何地方都没有加载P::Hb2::BaseMetric类(假设它不在P::Hb2Utils文件中)。建议解决方法:将use base ...改为use parent ...,因为这会自动加载该类的文件。

此外,base编译指示正在逐步淘汰 - 它只与fields编译指示一起使用才相关,而这是一种错误导向的尝试,旨在使面向对象编程更容易。


谢谢,不幸的是我被困在使用相当老的 Perl 上,其中 parent 不可用。 - Kevin
1
您应该能够在旧版 Perl 上从 CPAN 安装 parent - friedo
3
基类自动加载也是如此。基类与父类的主要区别在于基类可以悄无声息地失败。 - ikegami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接