我有一个模块作为其他几个模块的基础:
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.
答案 0 :(得分:2)
您无法加载P::Hb2::BaseMetric
类(假设它不在P::Hb2Utils
文件中)。建议的解决方法:将use base ...
更改为use parent ...
,因为这会自动加载该类的文件。
此外,base
编译指示正在逐步淘汰 - 仅与fields
编译指示相关,这是一种不明智的OOP尝试。