2011-03-02 49 views
2

为什么我无法在以下代码中使用子对象调用父代的testmethod?Perl OO问题,继承 - 调用父方法

use strict; 
    use Data::Dumper; 

    my $a = C::Main->new('Email'); 
    $a->testmethod(); 

    package C::Main; 


    sub new { 
     my $class = shift; 
     my $type = shift; 
     $class .= "::" . $type; 
     my $fmgr = bless {}, $class; 
     $fmgr->init(@_); 
     return $fmgr; 
    } 

    sub init { 
     my $fmgr = shift; 
     $fmgr; 
    } 

    sub testmethod { 
     print "SSS"; 
    } 

    package C::Main::Email; 
    use Net::FTP; 

    @C::Main::Email::ISA = qw(C::Main); 

    sub init { 
     my $fmgr = shift; 
     my $ftp = $fmgr->{ftp} = Net::FTP->new($_[0]); 
     $fmgr; 
    } 

    package C::Main::FTP; 
    use strict; 
    use Net::FTP; 

    @C::Main::Email::FTP = qw(C::Main); 

    sub init { 
     my $fmgr = shift; 
     $fmgr; 
    } 
+2

你不需要在每个包中重复'use strict;'。因为'strict'是一个词汇范围的编译指示,所以直到当前范围结束时才有效。包声明不会创建一个范围,所以如果'strict strict;'被放置在文件的顶部,它就在整个文件的范围内。 – 2011-03-02 21:40:06

回答

5

这是因为分配到@ISA是在运行时完成,因此在您尝试调用该方法。

你可以把它通过BEGIN周围,移动它来编译时间工作:

BEGIN { our @ISA = qw(C::Main) } 

,或者你可以做

use base qw(C::Main); 

这也是在编译时完成的。这两种变体都能解决您的问题。

+2

然而,我同意,从我读到的,'使用父母......'现在比'使用基地...'更受欢迎。 – 2011-03-02 22:24:51

+0

@Joel - 我听说'base'有一些问题,并且试图解决太多问题,尽管我从来没有将它用于继承以外的其他任何事情。至少根据'Module :: CoreList','parent'在5.10.1中也是核心。 – bvr 2011-03-03 05:28:06

0

如果您使用Perl编写新的OO代码,请使用Moose!

使用驼鹿后回到'使用基地'就像是回到了20世纪50年代。