Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically include Perl modules without using eval?

Tags:

module

perl

eval

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?

like image 381
user226723 Avatar asked Dec 16 '09 19:12

user226723


People also ask

Which function in Perl allows you to include a module file or a module?

A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" );


1 Answers

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 = $@;     # ... }; 
like image 73
Michael Carman Avatar answered Oct 03 '22 19:10

Michael Carman