我创建了以下2个文件,但是当我运行sample.pl时,它给了我以下错误
Can't locate object method "new" via package "sample" at sample.pm line 14.
感谢任何帮助。
感谢。
package sample;
use strict;
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my %fields = (
Debug => 0,
Error => undef,
@_,
);
my $self = bless $proto->SUPER::new(%fields), $class;
return $self;
}
1;
sample.pl
#!/usr/bin/perl
use strict;
use sample;
my $obj = sample->new();
print "Howdy, sample\n";
答案 0 :(得分:3)
伪类SUPER
引用它出现的包的父类(不是调用它的对象的父类!)。你没有父类。添加父类以查看它是否有效。这是一个有一些修改的例子。
#######################
package ParentSample;
use strict;
use warnings;
sub new {
my( $class, %fields ) = @_;
# some debugging statements so you can see where you are:
print "I'm in ", __PACKAGE__, " for $class\n";
# make the object in only one class
bless \%fields, $class;
}
#######################
package Sample;
use strict;
use warnings;
use base qw(ParentSample);
sub new {
my( $class ) = shift;
# some debugging statements so you can see where you are:
print "I'm in ", __PACKAGE__, " for $class\n";
my %fields = (
Debug => 0,
Error => undef,
);
# let the parent make the object
$class->SUPER::new( %fields );
}
#######################
package main;
use strict;
use warnings;
my $obj = Sample->new( cat => 'Buster' );
print "Howdy, sample\n";
奇怪的是,这个错误信息在最新版本的perl中得到了更好的效果。您的旧perl不会在邮件中添加SUPER
:
$ perl5.8.9 sample
Can't locate object method "new" via package "sample" at sample line 14.
$ perl5.10.1 sample
Can't locate object method "new" via package "sample" at sample line 14.
$ perl5.12.1 sample
Can't locate object method "new" via package "sample::SUPER" at sample line 14.
$ perl5.14.1 sample
Can't locate object method "new" via package "sample::SUPER" at sample line 14.
答案 1 :(得分:1)
您的 sample.pm 文件中没有任何use base
- 它没有继承任何其他软件包 - 您希望$proto->SUPER
是谁?
答案 2 :(得分:1)
您可以自己修改@ISA数组并加载模块,而不是使用base:
所以
use base "ParentSample";
可以替换为:
require ParentSample;
@ISA = ("ParentSample");
修改@ISA时,加载模块很重要,否则它不会起作用。基本负载适合你。