Autoload-AUTOCAN

 view release on metacpan or  search on metacpan

lib/Autoload/AUTOCAN.pm  view on Meta::CPAN

=head1 CONFIGURING

L<Autoload::AUTOCAN> accepts import arguments to configure its behavior.

=head2 functions

C<AUTOLOAD> affects standard function calls in addition to method calls. By
default, the C<AUTOLOAD> provided by this module will die (as Perl normally
does without a defined C<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 C<functions> as an import argument, and the installed
C<AUTOLOAD> will autoload functions using C<AUTOCAN> from the current package,
rather than using the first argument as an invocant.

  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

=head2 install_subs

By passing C<install_subs> as an import argument, any autoloaded function or
method returned by C<AUTOCAN> will be installed into the package, so that
future invocations do not need to go through C<AUTOLOAD>. This should not be
used if the autoloaded code is expected to change in subsequent calls to
C<AUTOCAN>, as the installed version will be called or returned by C<can>
directly.

  package My::Class;
  use Moo;
  use Autoload::AUTOCAN 'install_subs';
  
  sub AUTOCAN {
    my ($self, $method) = @_;
    my $hash = expensive_calculation($method);
    return sub { $hash };
  }
  
  # elsewhere
  my $obj = My::Class->new;
  $obj->foo; # sub foo installed in My::Class
  $obj->foo; # not autoloaded anymore

=head1 CAVEATS

If you use L<namespace::clean>, it will clean up the installed C<AUTOLOAD>
function. To avoid this, either use this module B<after> L<namespace::clean>,
or add an exception for C<AUTOLOAD> as below.

  use Autoload::AUTOCAN;
  use namespace::clean -except => 'AUTOLOAD';

This issue does not seem to occur with L<namespace::autoclean>.

=head1 BUGS

Report any issues on the public bugtracker.

=head1 AUTHOR

Dan Book <dbook@cpan.org>

=head1 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)

=head1 SEE ALSO

L<AutoLoader>, L<SelfLoader>



( run in 3.796 seconds using v1.01-cache-2.11-cpan-75ffa21a3d4 )