How can I dynamically include Perl modules without using eval?

Use require to load modules at runtime. It often a good idea to wrap this in a block (not string) eval in case the module can’t be loaded.

eval {
    require My::Module;
    My::Module->import();
    1;
} or do {
   my $error = $@;
   # Module load failed. You could recover, try loading
   # an alternate module, die with $error...
   # whatever's appropriate
};

The reason for the eval {...} or do {...} syntax and making a copy of $@ is because $@ is a global variable that can be set by many different things. You want to grab the value as atomically as possible to avoid a race condition where something else has set it to a different value.

If you don’t know the name of the module until runtime you’ll have to do the translation between module name (My::Module) and file name (My/Module.pm) manually:

my $module="My::Module";

eval {
    (my $file = $module) =~ s|::"https://stackoverflow.com/"g;
    require $file . '.pm';
    $module->import();
    1;
} or do {
    my $error = $@;
    # ...
};

Leave a Comment