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

Sam Lee picture Sam Lee · Jul 21, 2009 · Viewed 23.8k times · Source

What is the difference between doing use My::Module and require My::Module?

Answer

Chas. Owens picture Chas. Owens · Jul 21, 2009

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;
}