There are two strategies -- either examine the symbol table to initialize on creation, or make use of AUTOLOAD and test with can
. AUTOLOAD can be messier as you have to deal with the case where the method isn't there:
sub AUTOLOAD {
my $self = shift;
my $method = $AUTOLOAD;
$method =~ s/.*://; # strip package name
if ( $self->{'result'}->can($method) ) {
return $self->{'result'}->$method(@_);
} else {
croak "Unknown method : $method";
}
}
But the symbol table trick is brittle, as if they're using inheritance, you won't see the inherited methods without walking up @ISA, too. (and even if they're not -- they might start using inheritance in the future, which results in things breaking)
...
Typically, when you're trying to copy another module's interface, you've got a case of inheritance, so you might want to ask yourself what the relationship is between ::d
and ::e
:
a::b::c::d
is an a::b::c::e
a::b::c::d
uses a::b::c::e
If it's an is-a relationship, it's typically better suited to inheritance (although you might have wrappers around each of the methods, and still need to go through this whole exercise anyway). If it's a uses relationship, odds are you don't want to inherit from every last method they have, and can just hard code a list (although, the list might change if the used class is updated)
foreach my $method ( @list_of_methods_to_copy ) {
*{$method} = sub {
my $self = shift;
return $self->{'results'}->$method(@_);
}
}