Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I seem to be missing something with regard to inheritance. In the following example, shouldn't it print
new[A] new[B]
? Instead, it prints
new[A] Can't locate object method "new" via package "B" at test.pl line 6.
Here's the code:
#! /usr/bin/perl use strict; use warnings; A->new(); B->new(); package A; sub new { print "new[$_[0]]\n"; } package B; use vars qw(@ISA); @ISA = qw/A/;
I'm not sure why B isn't getting A's new() method if B is an A.

Replies are listed 'Best First'.
Re: Inheritance question
by pc88mxer (Vicar) on Jul 11, 2008 at 17:36 UTC
    Move your calls to new to the end of the file.

    Or, replace: @ISA = qw/A/ with: use base 'A'.

    The problem is that @ISA = qw/A/ is not being run at compile time, and so package B isn't completely set up before you call B->new().

Re: Inheritance question
by Joost (Canon) on Jul 11, 2008 at 17:36 UTC
      Son of a gun. I'd like to thank pc88mxer and FunkyMonk for their accurate and helpful responses and extend a special thanks to Joost for answering the question I didn't ask: "Why doesn't my original version of this test script, with A and B in seperate pm files work?". The answer is, of course, when my original script did this:
      #! /usr/bin/perl use strict; use warnings; use A; use B; A->new(); B->new();
      the runtime was finding the standard package B and not my test package. Thanks again!
Re: Inheritance question
by FunkyMonk (Bishop) on Jul 11, 2008 at 17:38 UTC
    Wrap your packages inside a BEGIN { ... } block and they'll work fine.

    Update:

    @ISA = qw/a/ needs to be run before you try to use the inheritance it defines. This doesn't happen in your orignal code, but the addition of the BEGIN block forces perl to compile and run the block before your calls to new.


    Unless I state otherwise, all my code runs with strict and warnings