in reply to Trying to re-use code at different levels of an inherited object.

I am no OO wizard and i really don't fully understand what you are trying to accomplish. I am intriqued by the question however, and i toyed around trying to find a solution. From what i can gather, you are trying to call SUPER after you have already 'backed up' to the SUPER object - not a recommended thing to do.

Instead, how about a more traditional polymorphic approach:

package Foo; use strict; sub new { bless {}, shift(); } sub do_something { my $self = shift; my $name = shift || 'foo'; return make_do_something($name); } sub make_do_something { my $name = shift; return sub { my $self = shift; print "Foo $name!!!\n"; } } 1; ############################################## package Bar; use strict; use base 'Foo'; sub new { bless {}, shift(); } sub do_something { my $self = shift; return $self->SUPER::do_something('bar'); } 1;
I _think_ this will accomodate your needs ...

This is my test script. The big difference is that the do_something() method returns a code ref, so you need to add some syntax:

#!/usr/bin/perl -w use strict; use Foo; use Bar; $_->do_something()->() for (new Foo, new Bar);
The reason why is, well - i don't know exactly what you are trying to accomplish by returning a sub in your make_do_something() method. If the only reason you do that is to create a method, then you can use this code and just drop make_do_something() completely. Everything you need is in Foo::do_something(). Hope this helps.

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: (jeffa) Re: Trying to re-use code at different levels of an inherited object.
by ehdonhon (Curate) on Jan 29, 2002 at 09:19 UTC

    If it were that simple, I'd be set :)

    I'm sorry that I didn't make sense the first time. The issue is that I want to recursively call SUPER::do_something all the way up to the top most superclass that can do_something. I could do that like this:

    package A; sub do_something { print "Foo\n"; } package B; @ISA = ( A ); sub do_something { my $self = shift; $self->SUPER::do_something(); print "Bar\n"; }

    But, I'd end up with a whole bunch of stub modules sitting around that were all almost identical, save a literal constant ("Foo\n" vs. "Bar\n") and the fact that A does not call SUPER::do_something(). Shouldn't I be able to abstract this all away so that I only have to implement do_something() once and not worry about making stubs in all my modules? As I said, I'm not very experienced with closures, but I thought this is what they were all about. It would be more maintainable if I could change the requirements of do_something() in the future and NOT have to go change every one of my stubs.

    I guess I should just suck it up and write the stubs.