Reputation: 779
I have a module that is acting as the base for several others:
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;
I'm trying to inherit from it with this:
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;
and trying to call it with this:
#!/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);
But when i do this I get the error:
Can't locate object method "new" via package "P::Hb2::CPUInfo" at test.pl line 9.
Upvotes: 3
Views: 141
Reputation: 57600
Nowhere do you load the P::Hb2::BaseMetric
class (assuming it does not live in the P::Hb2Utils
file). Suggested fix: Change use base ...
to use parent ...
, as this auto-loads the file for that class.
Also, the base
pragma is being phased out – it is only relevant in combination with the fields
pragma, an ill-guided attempt towards easier OOP.
Upvotes: 2