http://qs321.pair.com?node_id=131311


in reply to Replacing namespaces

I'm quite new at OO and OO Perl so I may not quite grasp the problem but this looks like a good use of TheDamian's NEXT module. It basically allows your object to dispatch a method to all other objects in the hierarchy. The following code shows an example of how this might be done.
#!/usr/bin/perl use warnings; use strict; use NEXT; package Base; sub new { print "Base new\n"; my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; bless ($self,$class); return $self; } sub Base::method { my $self = shift; my $data = shift || 0; print "$self: Base method, data = $data\n"; return 'Base'; } sub Base::DESTROY { my $self = shift; print "$self: Base DESTROY\n"; } package A; use base qw(Base); sub new { print "A new\n"; my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; bless ($self,$class); return $self; } sub A::method { my $self = shift; my $data = shift || 0; print "$self: A method, data = $data\n"; return 'A' if $data =~ /A/; #it's my data, so handle it $self->NEXT::ACTUAL::method($data); #otherwise dispatch to the nex +t class } sub A::DESTROY { my $self = shift; print "$self: A DESTROY\n"; $self->NEXT::UNSEEN::DESTROY(); } package B; use base qw(A); sub new { print "B new\n"; my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; bless ($self,$class); return $self; } sub B::method { my $self = shift; my $data = shift || 0; print "$self: B method, data = $data\n"; return 'B' if $data =~ /B/; #it's my data, so handle it $self->NEXT::ACTUAL::method($data); #otherwise, dispatch to next c +lass; } sub B::DESTROY { my $self = shift; print "$self: B DESTROY\n"; $self->NEXT::UNSEEN::DESTROY(); } package main; my $obj = new B(); #this one will be handled by Base print "calling method with generic data\n"; my $return = $obj->method('foo data'); print "return value was $return\n"; #this one will get handled by A print "calling method with A's data\n"; $return = $obj->method('A data'); print "return value was $return\n"; #this one will get handled by B print "calling method with B's data\n"; $return = $obj->method('B data'); print "return value was $return\n";
When run this produces:
B new calling method with generic data B=HASH(0xa01116c): B method, data = foo data B=HASH(0xa01116c): A method, data = foo data B=HASH(0xa01116c): Base method, data = foo data return value was Base calling method with A's data B=HASH(0xa01116c): B method, data = A data B=HASH(0xa01116c): A method, data = A data return value was A calling method with B's data B=HASH(0xa01116c): B method, data = B data return value was B B=HASH(0xa01116c): B DESTROY B=HASH(0xa01116c): A DESTROY B=HASH(0xa01116c): Base DESTROY
Read the NEXT docs for details on how this works and the UNSEEN and ACTUAL parameters.