use - load module at compile time

Use use to load the module at compile time.

use MODULE_NAME;

The module name must be specified as a bare string. Strings enclosed in quotes or double quotes will not be accepted. Also, variable are not accepted.

# Specify the module name with a bare string
use CGI;

It is also standard practice to specify the function name after the module name to import the function into the current namespace.

# Import function
use File::Basename 'basename', 'dirname';

There is a require function in addition to use as a means to load a module, but when loading a module, usually use use. The module expects the import method to be called, so use will do it for you.

Processing executed by use

The following processing is executed by use. The case of File :: Basename is taken as an example.

# Process executed by use
BEGIN {
  require File::Basename;
  File::Basename->import(qw/basename dirname/);
}

The part enclosed in the BEGIN block is executed at compile time. require loads the module and imports that module as a method call.

How to not execute import

use will automatically perform the import. If you don't want to import, do the following:

# Do not execute import
use File::Basename();

How to pass variable to use

Since use can only accept bare strings, you need to be creative in passing variable. You need to use eval to recognize the variable name as a bare string.

Also, eval can perform dangerous processing, so make sure it does not contain harmful processing before executing it. If the module fails to load, an error message will be stored in $ @.

# Pass a variable to use

# Module name
my $module = 'AAA';

# Make sure it consists of only word characters
die "Invalid module name" if $module =~ /\W/;

# Load module
eval "use $module";

# What to do if module loading fails
die $@ if $@;

Related Informatrion