2

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;
}
1
  • 2
    You don't need to keep repeating use strict; in each package. Since strict is a lexically scoped pragma, it is in effect until the current scope ends. Package declarations do not create a scope, so if use strict; is placed at the top of a file, it is in scope for the entire file. Commented Mar 2, 2011 at 21:40

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I concur, however, from what I read, use parent ... is now preferred over use base ....
@Joel - I heard that base has some problems and somehow is trying to solve too much, although I never used it for anything else than inheritance. parent also came core in 5.10.1, at least according to Module::CoreList.
0

If you're writing new OO code in Perl, use Moose!

Returning to 'use base' after having used Moose is like going back to the 1950s.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.