Chapter 43. Autoloading Perl Code
Randy J. Ray
Would you prefer to load a library of 10, 20, or more routines all at once, or only as needed? Perl provides a procedure called autoloading that specifies what happens when a program encounters a subroutine that is not currently defined. You do this using two modules: AutoLoader and AutoSplit.
Why Autoload?
I first took an interest in the AutoLoader when converting a lot of legacy code from Perl 4 to 5. One of the libraries that particularly frustrated me was a front end to some RCS utilities. The overhead was too high; in a library of 40–50 subroutines, I rarely needed more than two-thirds in a given execution, and sometimes just a few. Not only did I want to avoid the penalty of loading and parsing the whole library, I wanted to keep the unneeded routines from being loaded in the first place.
One of the ways in which use
differs from require
is that it loads (that is, reads and compiles) the module at compile time, before Perl runs the script. In Perl 4, which doesn’t have use
, I deferred loading the RCS library as long as possible by performing other tasks first, such as validating command-line usage, and so on. But as I upgraded, I realized that to take advantage of Perl 5, I needed to turn libraries into modules, and design my modules around the tools that Perl provides. As a result, I turned to the AutoLoader and AutoSplit libraries.
I’ll use a smaller example for this article, a module I maintain called Image::Size (available on CPAN). ...
Get Computer Science & Perl Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.