In Perl, two main operators are used to include modules — use and require.
use — Includes the module at compile-time. It executes immediately when reading the Perl file, loading the module into scope and calling the import method (if it exists).
require — Loads the module at run-time.
require $some_module;).Example:
use MyModule; # compile-time; calls import require 'MyModule.pm'; # run-time; no import
Can
usebe used with a variable module name, e.g.,use $module_name;?
Answer: No. The use operator requires a statically known module name at compile-time, while require is suitable for variable names.
Example:
my $module = 'Some::Plugin'; require $module; $module->import();
Story
A project was written with a large number of dynamically loaded plugins. One developer mistakenly used 'use $plugin', which caused a compile-time error. It was later discovered that loading was only possible through require, and only then calling import.
Story
In a large Perl service, part of the libraries were loaded through 'require', without calling import. The variables and functions that were relied on were not imported into the namespace, and the code began to finish with undefined subroutine errors.
Story
A developer tried to include a large block of code inside a function using 'use', expecting the module to load only when necessary, but in practice, the module was picked up at startup, leading to unnecessary memory consumption.