Autoload::AUTOCAN - Autoloading the easy way

Autoload can be a very powerful tool in Perl, though often you should first consider if there's a better way; Autoload is not necessarily the best solution for cases where you just need to generate many methods by name, and definitely is not the best solution for "wrapping" static methods. But if your use-case does necessitate methods created on the fly, I have released Autoload::AUTOCAN to make this easier to get right.

Simply define an 'AUTOCAN' method in your class, which functions like the built-in 'can' method, and returns either a code reference or undef. Autoload::AUTOCAN will install an 'AUTOLOAD' function and a 'can' method that correctly delegate to 'AUTOCAN'. When a method is called that has not been defined on the class, the result of AUTOCAN will be run instead, or if AUTOCAN returns undef, it will die with the expected error message when a nonexistent method is called. The 'can' method is also important, as it is often used to check if it is possible to call a method on an object or class, so without this definition it will appear that your class does not have any of the methods provided by autoload.

As AUTOLOAD actually operates on all function calls and not just method calls, any nonexistent function call that is not called as a method will normally die with the standard error message. For packages which are not object classes, there is an alternative operation mode by passing the import parameter 'functions', which will delegate to AUTOCAN for any function call in the package, with error messages more appropriate for standard function calls.

Autoload::AUTOCAN does not cover all possible uses of autoloading, such as the AutoLoader and SelfLoader modules provide, but covers the most common modern usage in my opinion. Instead of rolling your own and dealing with the nuances of error messages and the 'can' method, give AUTOCAN a try next time.

Leave a comment

About Grinnz

user-pic I blog about Perl.