In Perl, what is the difference between use and require for loading a module?

The use function:

use ModuleName;

is equivalent to the following code using the require function:

BEGIN {
    require ModuleName;
    ModuleName->import;
}

The BEGIN block causes this code to run as soon as the parser sees it. The require loads the module or dies trying. And then the import function of the module is called. The import function may do all sorts of things, but it is common for it to load functions into the namespace that used it (often with the Exporter module).

It is important to note that import will not be called in this case:

use ModuleName ();

In that case, it is equivalent to

BEGIN {
    require ModuleName;
}

Leave a Comment

tech