require - load module at runtime
Use require to load modules at runtime . Use loads the module at compile time, while require loads it at run time.
# Load module require module name
The module name must be specified as a bare string. Strings enclosed in quotes or double quotes will not be accepted. It also does not accept variable.
# Specify the module name with a bare string require CGI;
When you load a module, you can use the functions described in the loaded module with the fully qualified name.
require Carp; # You can use the carp module's croak function with a fully qualified name. Carp::croak ("croak function");
The standard way to load a module is to use use, but there are times when you want to use require. If you use use, all modules will be loaded at compile time. Therefore, if the module is huge, it will take extra time to compile.
If a module is not required and is a large module, you may be able to mitigate the performance impact by loading it at runtime using require as needed.
Example
This is an example using require.
# Load the Carp module. require Carp;
require will import the module at runtime. This is useful if you want to selectively import modules.
For example, if you want to process according to the extension, you only need one of the modules that parses the csv file and the module that parses the xml.
In such a case, if you write as follows, you can load fewer modules.
if ($ext eq '.csv') { require Text::CSV; # ... } elsif ($ext eq '.xml') { require XML::Simple; # ... }
Less module loading means faster boot times and less memory usage. With use, all modules will be loaded at compile time, even if they are written in a conditional branch such as an if statement.