Why not adopt me?
NAME
Sub::Auto - declare individual handlers for AUTLOADed subs, respecting can and inheritance
SYNOPSIS
use Sub::Auto;
autosub /^get_(\w+)$/ {
my ($what, @pars) = @_;
print "Getting $what...\n";
}
autosub /^set_(\w+)_(\w+)$/ {
my ($adjective, $noun, @pars) = @_;
print "Setting the $adjective $noun\n";
}
autosub handle_foo_events /foo$/ {
my ($subname, @pars) = @_;
print "Called $subname to do something to a foo\n";
}
get_foo();
if (__PACKAGE__->can('set_blue_cat')) { ... }
DESCRIPTION
AUTOLOAD
, like other languages' method-missing
features is a useful feature for those situations when you want to handle sub or method calls dynamically, and can't pre-generate the subroutines with accessor generators.
To be sure, this is almost never the case, but occasionally, AUTOLOAD
is convenient.
Well, "convenient" is a strong word, writing sub AUTOLOAD
handlers is mildly unpleasant, and doesn't handle inheritance and can
by default.
Using Sub::Auto
you can:
Declare multiple handlers, each responding to calls matching a given regular expression.
Optionally name your handler, for clarity, or because you want to call it directly.
Ensure that unhandled methods get dealt with by the next class in the inheritance chain.
USAGE
autosub
autosub [name] /regex/ { ... }
If the regex contains capturing parentheses, then each of those items will be prepended to the sub's argument list. For example:
autosub /(\w+)_(\w+)/ {
my ($verb, $noun, @params) = @_;
print "$verb'ing $noun - " . join ','=>@params;
}
jump_up('one', 'two'); # prints "jump'ing up - one,two"
If the matching regex didn't have any capturing parens, the entire method name is passed as the first argument.
The name of the sub is optional. It registers a normal subroutine or method with that name in the current package. Nothing will be automatically prepended to a call to this method!
autosub foo /(\w+)_(\w+)/ {
my ($verb, $noun, $one,$two) = @_;
print $one + $two;
}
foo (undef,undef, 1, 2);
SEE ALSO
Class::AutoloadCAN by Ben Tilly, does all the heavy lifting.
Devel::Declare by Matt Trout provides the tasty syntactic sugar.
http://greenokapi.net/blog/2008/07/03/more-perl-hate-and-what-to-do-about-it-autoload/
Class::Accessor or various other method generators that are a saner solution in general than using AUTOLOAD at all.
AUTHOR AND LICENSE
(c) 2008 osfameron@cpan.org
This module is released under the same terms as Perl itself.