NAME
Autoload::AUTOCAN - Easily set up autoloading
SYNOPSIS
package My::Class;
use Moo; # or object system of choice
use Autoload::AUTOCAN;
has count => (is => 'rw', default => 0);
sub increment { $_[0]->count($_[0]->count + 1) }
sub AUTOCAN {
my ($self, $method) = @_;
return sub { $_[0]->increment } if $method =~ m/inc/;
return undef;
}
1;
# elsewhere
my $obj = My::Class->new;
$obj->inc;
say $obj->count; # 1
$obj->increment; # existing method, not autoloaded
say $obj->count; # 2
$obj->do_increment;
say $obj->count; # 3
$obj->explode; # method not found error
DESCRIPTION
Autoloading is a very powerful mechanism for dynamically handling function calls that are not defined. However, its implementation is very complicated. For the simple case where you wish to allow method calls to methods that don't yet exist, this module allows you to define an AUTOCAN
method which will return either a code reference or undef
. Autoloaded method calls will call AUTOCAN
and then run the returned method, or throw the expected error if undef
is returned, so you can generate code or delegate the method call as desired.
AUTOLOAD
affects standard function calls in addition to method calls. By default, the AUTOLOAD
provided by this module will die (as Perl normally does without a defined AUTOLOAD
) if a nonexistent function is called without a class or object invocant. If you wish to autoload functions instead of methods, you can pass functions
as an import argument, and the installed AUTOLOAD
will attempt to autoload functions using AUTOCAN
from the current package.
package My::Functions;
use Autoload::AUTOCAN 'functions';
sub AUTOCAN {
my ($package, $function) = @_;
return sub { $_[0]x5 } if $function =~ m/dup/;
return undef;
}
# elsewhere
say My::Functions::duplicate('foo'); # foofoofoofoofoo
say My::Functions::foo('bar'); # undefined subroutine error
BUGS
Report any issues on the public bugtracker.
AUTHOR
Dan Book <dbook@cpan.org>
COPYRIGHT AND LICENSE
This software is Copyright (c) 2017 by Dan Book.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)