package Foo; use strict; use vars qw($AUTOLOAD); use Carp qw(croak); sub new { bless {}, __PACKAGE__ } sub add_method { my ($self, $name, $code) = @_; ### This following chunk could use Scalar::Util::blessed ### if they have perl 5.8 installed. We will operate without it if (! ref $code) { # scary and sort of ugly but thats what the OP wanted $code = eval $code; } # (! Scalar::Util::reftype($code) ne 'CODE') { if (! UNIVERSAL::isa($code, 'CODE')) { croak "Usage : add_method(method => sub {})\n add_method(method => 'sub {}')"; } $self->{'_methods'}->{$name} = $code; } sub AUTOLOAD { my $self = shift; my $name = $AUTOLOAD =~ /(\w+)$/ ? $1 : croak "Invalid method \"$AUTOLOAD\""; my $code = $self->{'_methods'}->{$name} || croak "No such method \"$name\" via package ".__PACKAGE__; $self->$code(@_); } my $foo = Foo->new; $foo->add_method(bar => sub { print "bar\n" }); $foo->add_method(baz => 'sub { print "baz\n" }'); $foo->bar; $foo->baz;