2011-07-15 34 views
1

我創建了以下2個文件,但是當我運行sample.pl,它給我下面的錯誤 Can't locate object method "new" via package "sample" at sample.pm line 14.的Perl - SUPER - 無法找到對象的方法

任何幫助表示讚賞。

謝謝。

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

你在哪裏有'ref($ proto)|| $ proto'來自? – daxim

回答

1

您沒有任何use basesample.pm文件 - 它沒有繼承任何其他包裝 - 誰做你期待$proto->SUPER是?

2

僞類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

而不是使用基礎的你也可以modity @ISA數組和加載模塊自己:

所以

use base "ParentSample"; 

可更換與:

require ParentSample; 
@ISA = ("ParentSample"); 

修改@ISA時,加載模塊很重要otherwi它不會工作。基本負載它爲你。

相關問題