我有一个名为RuleObject的基础对象和一个从名为RuleObjectString继承的对象.我在RuleObjectString中有一个新方法,我想在我使用该对象的代码中调用它.但是我得到了错误.'无法找到对象方法"比较"来自./testobject.pl第10行的包"RuleObject".但我不是在创建一个RuleObject.我正在创建一个RuleObjectString.我在这做错了什么?
testobject.pl
1 #! /usr/bin/perl
2
3 use strict;
4
5 use RuleObjectString;
6
7 my $s = RuleObjectString->new();
8 $s->value('stuff goes here');
9
10 if ($s->compare('stuff')){
11 print "MATCH!\n";
12 }else{
13 print "no match :(\n";
14 }
Run Code Online (Sandbox Code Playgroud)
RuleObject.pm
package RuleObject;
our @ISA = qw/Exporter/;
our @EXPORT = qw/new/;
use strict;
sub new{
my $class = shift;
my $self;
$self->{value} = undef;
bless $self;
return $self;
}
sub value{
my $self = shift;
my $value = shift;
if ($value){
$self->{value} = $value;
}else{
return $self->{value};
}
}
Run Code Online (Sandbox Code Playgroud)
RuleObjectString.pm
package RuleObjectString;
our @ISA = qw/RuleObject/;
our @EXPORT = qw/compare/;
use strict;
sub compare{
my $self = shift;
my $compareto = shift;
return $self->value() =~ /$compareto/;
}
Run Code Online (Sandbox Code Playgroud)
mob*_*mob 12
我认为jmcneirney走在正确的轨道上.在你的RuleObject
构造函数中,你说
bless $self;
Run Code Online (Sandbox Code Playgroud)
这是一样的
bless $self, __PACKAGE__;
Run Code Online (Sandbox Code Playgroud)
要么
bless $self, 'RuleObject'
Run Code Online (Sandbox Code Playgroud)
但你想要的是让对象得到祝福RuleObjectString
.所以你要做的就是说
bless $self, $class
Run Code Online (Sandbox Code Playgroud)
现在
RuleObject->new()
RuleObjectString->new()
Run Code Online (Sandbox Code Playgroud)
将调用相同的构造函数,但第一次调用返回的对象将被祝福为a RuleObject
,第二个对象将被祝福为a RuleObjectString
.
这是2012年,所以你应该考虑使用适当的OOP解决方案,而不是重新重新发明轮子.
通过使用Moose,解决方案看起来像这样(未经测试):
RuleObject.pm
package RuleObject;
use Moose;
has 'value' => ( isa => 'Str', is => 'rw', required => 0, default => '' );
1;
Run Code Online (Sandbox Code Playgroud)
RuleObjectString.pm
package RuleObjectString;
use Moose;
extends 'RuleObject';
sub compare {
my $self = shift;
my $compareto = shift;
return $self->value =~ /$compareto/;
}
1;
Run Code Online (Sandbox Code Playgroud)
简单!:)