Delaying use Until Run Time


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.


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


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:

    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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.