Hello,
I have an a situation where I have multiple levels of derived objects that all need to implement the same method (in my simplified case below, I have named it 'do_something'). Each package knows how to 'do_something' with the data that it cares about, and it needs to recursively tell its parent in the inheritance tree to do_something with the data as well. For simplicity sake, assume that each class only inherits from one class (no multiple inheritance).
After I got started coding all of the do_something's, I found the code was so similar in each case, that it would be a crime not to just write it once and re-use the code. I thought I could do this via closures. But being a newbie to closures, I appear to be doing something wrong.
Here is the model I'm trying to implement:
#file: Foo.pm package Foo; *do_something = &make_do_something( 'foo' ); sub make_do_something { my $name = shift; ## In my real code, I have other interesting params here ## that gives my sub the information to do the ## things that each class knows about. return sub { my $self = shift; if ( $name ne 'foo' ) { print "Not foo\n"; $self->SUPER::do_something(); } print "Foo $name!!!\n"; return 1; } } __END__ #File: Bar.pm package Bar; use base 'Foo'; *do_something = &Foo::make_do_something( 'bar' ); sub new { bless {}, shift(); } __END__ #!/usr/local/bin/perl #File: foobar.pl use Foo; use Bar; $b = new Bar(); $b->do_something(); __END__
Now, I was hoping that I would see something like this:
Not foo Foo foo!!! Foo bar!!!Regretfully, I'm getting this:
Not foo Can't locate object method "do_something" via package "Foo" (perhaps you forgot to load "Foo"?) at Foo.pm line 13.Is it possible to do what I'm trying to do here? What am I doing wrong?
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |