to start, try using the magic of AUTOLOAD
#!/usr/bin/perl
use strict;
use warnings;
package Thing;
use Quantum::Superpositions;
sub new {
my ($class,$txt) = @_;
return bless \$txt, $class;
}
sub txt {
my ($self) = @_;
return $$self;
}
my @allowed = qw[
findActor
addActor
findMovie
addMovie
];
sub AUTOLOAD {
my ($self, @args) = @_;
use vars '$AUTOLOAD';
(my $funcname = $AUTOLOAD) =~ s/.*:://;
unless ($funcname eq any(@allowed)) {
die "don't know how to $funcname on ", $self->txt, $/;
}
warn "doing $funcname on ", $self->txt, " with @args$/";
}
sub DESTROY { } # for AUTOLOAD happiness
1;
package main;
my $b = Thing->new("bob");
my $c = Thing->new("ralph");
$b->findActor("quincy");
$c->addActor("mary");
$b->doActor("what?");
__END__
doing findActor on bob with quincy
doing addActor on ralph with mary
don't know how to doActor on bob
later down the line you can loop through your supported functions and create anonymous sub's and attach them directly to your package namespace with GLOB magic.
package Thing2;
sub new {
my ($class,$txt) = @_;
return bless \$txt, $class;
}
sub txt {
my ($self) = @_;
return $$self;
}
my @allowed = qw[
findActor
addActor
findMovie
addMovie
];
foreach my $funcname (@allowed) {
my $sub = sub {
my ($self, @args) = @_;
warn "doing $funcname on ", $self->txt, " with @args$/";
};
my $pkgfunc = __PACKAGE__ . "::$funcname";
no strict 'refs';
*$pkgfunc = $sub;
}
1;
package main;
my $b = Thing2->new("bob");
my $c = Thing2->new("ralph");
$b->findActor("quincy");
$c->addActor("mary");
$b->doActor("what?");
__END__
doing findActor on bob with quincy
doing addActor on ralph with mary
Can't locate object method "doActor" via package "Thing2" (perhaps you
+ forgot to load "Thing2"?) at ./qs.pl line 76.