Programming Perl

Programming PerlSearch this book
Previous: 3.2.122 renameChapter 3
Functions
Next: 3.2.124 reset
 

3.2.123 require

require EXPR
require

This function asserts a dependency of some kind on its argument. (If EXPR is not supplied, $_ is used as the argument.)

If the argument is a string, this function includes and executes the Perl code found in the separate file whose name is given by the string. This is similar to performing an eval on the contents of the file, except that require checks to see that the library file has not been included already. (It can thus be used to express file dependencies without worrying about duplicate compilation.) The function also knows how to search the include path stored in the @INC array (see the section "Special Variables" in Chapter 2).

This form of the require function behaves much like this subroutine:

sub require {
    my($filename) = @_;
    return 1 if $INC{$filename};
    my($realfilename, $result);
    ITER: {
        foreach $prefix (@INC) {
            $realfilename = "$prefix/$filename";
            if (-f $realfilename) {
                $result = eval `cat $realfilename`;
                last ITER;
            }
        }
        die "Can't find $filename in \@INC";
    }
    die $@ if $@;
    die "$filename did not return true value" unless $result;
    $INC{$filename} = $realfilename;
    return $result;
}

Note that the file must return true as the last value to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise.

This operator differs from the now somewhat obsolete do EXPR operator in that the file will not be included again if it was included previously with either a require or do EXPR command, and any difficulties will be detected and reported as fatal errors (which may be trapped by use of eval). The do command does know how to do the @INC path search, however.

If require's argument is a number, the version number of the currently executing Perl binary (as known by $]) is compared to EXPR, and if smaller, execution is immediately aborted. Thus, a script that requires Perl version 5.003 can have as its first line:

require 5.003;

and earlier versions of Perl will abort.

If require's argument is a package name (see package), require assumes an automatic .pm suffix, making it easy to load standard modules. This is like use, except that it happens at run-time, not compile time, and the import routine is not called. For example, to pull in Socket.pm without introducing any symbols into the current package, say this:

require Socket; # instead of "use Socket;"

However, one can get the same effect with the following, which has the advantage of giving a compile-time warning if Socket.pm can't be located:

use Socket ();


Previous: 3.2.122 renameProgramming PerlNext: 3.2.124 reset
3.2.122 renameBook Index3.2.124 reset