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

Hi everyone,

I've run into a problem that I'm not quite sure how to describe.

In essence, I think I'm looking for a SUPRA class -- sort of a reverse of SUPER. Here's what I am trying to do: I have a child class that only has a subset of the methods of its parent. So let's say method finalize is called. It ends up going to the parent class.

This is where things get tricky. finalize calls another one of the class's methods, finalize_body. And, while the parent class has a finalize_body, so does the child class. Assuming the child class has a finalize_body method, I would like to move back to the child class and not use the parent's method.

Yet, I haven't been able to think of a way to do this without explicitly naming the child package. Moreover, I'd like for it to be setup in such a way where if the child does not have a finalize_body class, it will move down the tree of inheritance normally and use the parent's method instead.

Does that make sense? Is there a simple way to do what I'm trying to do?

Thanks for your help!

Replies are listed 'Best First'.
Re: Supra Class for Inheritance?
by ikegami (Patriarch) on Aug 21, 2010 at 00:59 UTC

    You get that behaviour by default.

    { package Parent; sub new { my ($class) = @_; return bless({}, $class); } sub finalise { my ($self) = @_; $self->finalise_body(); } sub finalise_body { my ($self) = @_; print(__PACKAGE__, "\n"); } } { package ChildWith; our @ISA = 'Parent'; sub finalise_body { my ($self) = @_; print(__PACKAGE__, "\n"); } } { package ChildWithout; our @ISA = 'Parent'; } { ChildWith ->new->finalise(); # ChildWith ChildWithout->new->finalise(); # Parent }

    In C++ term, methods of this type are called virtual methods.

      Thanks -- I was just totally overlooking the obvious solution. Even though I had made everything else OOP, I was calling finalize_body as just a straight subroutine. Doing $self->finalize_body does the trick. Thank you! Hard to believe that drove me crazy for so long. Sheesh!
Re: Supra Class for Inheritance?
by merlyn (Sage) on Aug 21, 2010 at 02:56 UTC
    I have a child class that only has a subset of the methods of its parent.
    Then it's not a child class. Fix your hierarchy.

    -- Randal L. Schwartz, Perl hacker

    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

      I think the OP meant the child class overrides only a subset.
Re: Supra Class for Inheritance?
by Anonymous Monk on Aug 21, 2010 at 00:47 UTC
      I'm sure I'm being dense, but I'm not sure how one might use NEXT for this task. Does it check the child class as well as the parents?