我还在学习OO Perl的基本原理。 我用一个基本的构造函数创建了一个名为BigBrother.pm的包。
package BigBrother;
use strict;
use warnings;
sub new {
my ($class, $args) = @_;
my $self = {
datacenter => $args->{datacenter},
testname => $args->{testname},
hostname => $args->{hostname},
ipaddress => $args->{ipaddress},
eventtime => $args->{eventtime},
responsetime => $args->{responsetime},
error => $args->{error} || ''
};
return bless $self, $class;
}
我还创建了两个方法:一个记录事件开始前的时间,另一个记录事件停止的时间。
sub setTimer {
my $self = shift;
my $start = `date +%s.%N`;
$self->{startTimer} = $start->startTimer;
}
sub endTimer {
my $self = shift;
my $end = `date +%s.%N`;
return $self->{endTimer} = $end->endTimer;
}
1;
在我的perl可执行脚本中,我有以下内容:
#!/usr/bin/perl -w
use warnings;
use strict;
use Xymon::Plugin::Server::Hosts;
use lib "/usr/lib/xymon/server/ext";
use BigBrother;
BEGIN {
$ENV{LD_LIBRARY_PATH}= "/usr/lib/xymon/server/ext/";
}
my $bigbro = new BigBrother;
my $ret = $bigbro->setTimer;
但是我在运行脚本时遇到以下错误:
# ./a.pl
Can't locate object method "startTimer" via package "1422368625.492495754
" (perhaps you forgot to load "1422368625.492495754
"?) at /usr/lib/xymon/server/ext/BigBrother.pm line 22.
这是BigBrother.pm的第22行
sub setTimer {
20 my $self = shift;
21 my $start = `date +%s.%N`;
22 $self->{startTimer} = $start->startTimer;
23 }
24
25 sub endTimer {
26 my $self = shift;
27 my $end = `date +%s.%N`;
28 $self->{endTimer} = $end->endTimer;
29 }
显然,我错过了一些东西。请有人澄清一下吗?
答案 0 :(得分:1)
my $start = `date +%s.%N`;
以上在$start
中存储字符串(不是对象)。将您的子更改为:
sub setTimer {
my $self = shift;
my $start = `date +%s.%N`;
$self->{startTimer} = $start;
}
sub endTimer {
my $self = shift;
my $end = `date +%s.%N`;
return $self->{endTimer} = $end;
}
答案 1 :(得分:0)
以下是两个相关的行:
21 my $start = `date +%s.%N`;
22 $self->{startTimer} = $start->startTimer;
您调用date
并将其输出作为字符串存储在标量变量$start
中。然后尝试在此非对象上运行方法startTimer
。这并不能解决完全正确的问题。
您是否在某处定义了startTimer
方法,或者您是否应该提供一个应该提供它的模块?