Delaying use Until Run Time

Problem

You have a module that you don’t need to load each time the program runs, or whose inclusion you wish to delay until after the program starts up.

Solution

Either break up the use into its separate require and import components, or else employ the use autouse pragma.

Discussion

Programs that check their arguments and abort with a usage message on error have no reason to load modules they’ll never use. This delays the inevitable and annoys users. But those use statements happen during compilation, not execution, as explained in the Introduction.

Here, an effective strategy is to place argument checking in a BEGIN block before loading the modules. The following is the start of a program that checks to make sure it was called with exactly two arguments, which must be whole numbers, before going on to load the modules it will need:

BEGIN {
    unless (@ARGV == 2 && (2 == grep {/^\d+$/} @ARGV)) {
        die "usage: $0 num1 num2\n";
    }
}
use Some::Module;
use More::Modules;

A related situation arises in programs that don’t always use the same set of modules every time they’re run. For example, the factors program from Chapter 2, needs the infinite precision arithmetic library only when the -b command-line flag is supplied. A use statement would be pointless within a conditional because it’s evaluated at compile time, long before the if can be checked. So we’ll use a require instead:

if ($opt_b) {
    require Math::BigInt;
}

Because Math::BigInt is an object-oriented module ...

Get Perl Cookbook 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.