perlperl-module

Perl OO Question, Inheritance - calling parent method


Why am I not able to call testmethod of parent using child object in the following code?

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;
}

Solution

  • It is because assignment into @ISA is done at runtime, thus after you try to call the method.

    You can make it work by surrounding by BEGIN, moving it to compile time:

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

    or you can do

    use base qw( C::Main );
    

    which is also done in compile time. Both variants do fix your problem.