1. Perl
  2. Module basics

Load the module by specifying the module name with a variable

It takes some ingenuity to specify the module name as a variable and load it. requere takes a string or a bare word as an argument. When require receives a string, it recognizes it as a filename. On the other hand, when it receives a bare word, it recognizes it as a module name.

# If the argument is a string, it is recognized as a file name.
require "Carp.pm";

# If the argument is a bare word, it is recognized as a module name.
require Carp;

Since require has such a specification, the argument is recognized as a file name. Therefore, to specify the module name as a variable and read it, write as follows.

my $module = "Carp";
eval "require $module;";

If you give a string to eval, executable statement in the string will be executed. "require $module;" is variable-expanded to require Carp ;. This will be executed by eval and the module will be loaded.

Related Informatrion