I need to dynamically include a Perl module, but if possible would like to stay away from eval due to work coding standards. This works:
$module = "My::module"; eval("use $module;");
But I need a way to do it without eval
if possible. All google searches lead to the eval
method, but none in any other way.
Is it possible to do it without eval
?
A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" );
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|::|/|g; require $file . '.pm'; $module->import(); 1; } or do { my $error = $@; # ... };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With