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

If I create a package like:
package Parent; sub identify { return name(); } sub name { return 'Parent'; } 1;
Thus, Parent::identify should return the string 'Parent'. How do I create a second class, 'Child', so that Child::identify returns the value returned by name() in the Child package?

Replies are listed 'Best First'.
Re: Overriding 'static' methods of a perl package
by Fletch (Bishop) on Sep 16, 2008 at 13:52 UTC

    Your problem is that you don't have methods, you just have plain vanilla subroutines which don't interact with inheritance at all. If you want inheritance you need to establish a subclass relationship using @ISA and actually make method calls. See perlboot, perltoot, and perltooc (and probably perlbot too, just for good measure).

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Overriding 'static' methods of a perl package
by Corion (Patriarch) on Sep 16, 2008 at 13:53 UTC

    For that to work, sub identify must be written differently, as a class method:

    package MyParent; sub identify { return $_[0]->name; }; sub name { return 'MyParent'; # or alternatively, return ref $_[0] || $_[0] }; package Child; use parent -norequire => 'MyParent'; sub name { return 'Child'; # or alternatively, return ref $_[0] || $_[0] };

    Update: Also set up inheritance between Child and MyParent.

      Let me clarify my omissions from my prevous post. Here's what I have at the present time:
      package Parent; sub identify { return name(); } sub name { return 'Parent'; } 1; package Child; use Parent; @ISA = qw(Parent); sub name { return 'Child'; } 1
      Parent::identify returns 'Parent' Child::identifiy returns nothing Parent::identify() returns 'Parent' Child::identify() generates an error (undefined subroutine)

        "You can't get there from here".

        Unless you use "object notation", and call your methods with a class or object instance, no inheritance will work.

        You could fake the stuff you want by trying AUTOLOAD trickery but down that road lies so much sorrow I won't even tell you how to do it.

        So you'll have to change Parent and Child in the way I outlined above.