我有一个模块作为其他几个模块的基础:
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.