in reply to Loading a module at runtime...

Perhaps you should rethink your approach, and go for require instead of use, and use an OO approach, even though you have no objects, by calling the subs as class methods. That way, you can get rid of the eval, and even have it pass strict without problem.

One problem when calling require with a variable scalar, is that the format must be different: the magic conversion you get when writing require Foo::Bar; no longer works: you have to convert 'Foo::Bar' to 'Foo/Bar.pm' yourself. So this should, basically, work:

use strict; our $module = 'Foo::Bar'; my $file = join('/', split /::/, $module) . '.pm'; require $file; $module->run();
Note that any class method ("run") you call this way, will get one extra argument prepended, in front of any of your own: the class name, the string that's currently in $module.

p.s. For reasons of sanity, I personally would prefer an extra root in front of the actual module names, for example 'MyDrivers' (bad example :-), so you actually load and run MyDrivers::Foo::Bar, if the user supplies the string 'Foo::Bar'. That way, you can make sure you can only load modules that are especially prepared to be used this way.

p.p.s. People using older perls than 5.6.0 should replace the 'our' with another appropriate solution (use vars or my), or simply not use strict :-). This has nothing to do with the functionality of the code I described here. I would think that should still work.

Replies are listed 'Best First'.
Re: Re: Loading a module at runtime...
by sixbyseven (Initiate) on Apr 08, 2003 at 10:41 UTC
    Just thought I'd add that, as far as I know, 'use' happens at compile time only, so you have to 'require' modules at runtime. Also, for OO modules, is there any need to do an import?
      Well, that depends on what the module wants to do, doesn't? I sometimes let OO modules export constants, or a subroutine that returns an object. And there are other things you might want to do in an import.

      Abigail