in reply to Best/possible ways to dynamically use modules
Conditionally loading a module is very easy. The only thing to avoid is a bare use statement, because use is executed at compile time. For example:
So, you can either eval a use statement, or require the module and then call import. (I prefer the second approach.)if ($use_socket) { use Socket; # oops! Socket will get loaded at compile-time # before $use_socket is even evaluated }
if ($use_socket) { eval "use Socket"; # ok: Socket gets loaded at run-time # if $use_socket is true }
if ($use_socket) { require Socket; # ok: Socket gets loaded at run-time Socket->import(); # if $use_socket is true }
However, you may need more than that, because you're planning to load the modules from a controller module. If the modules you're loading export anything, you probably want to export them into the package that called the controller module. That is, maybe you'll have the controller module load Socket, but then you want to call the Socket functions from the main script.
The Exporter module, which provides a basic import() method, also provides export_to_level(). export_to_level() does an import to a package farther up in the call tree. For modules which inherit from Exporter, such as the Socket module, you can call the export_to_level() method to get the behavior you need:
Unfortunately, not every module inherits from Exporter or defines its own export_to_level() method. CGI, for example, doesn't have an export_to_level() method. I'm afraid I don't know a good approach for a situation like this. But I hope this was enough to get to you started!if ($use_socket) { require Socket; Socket->export_to_level(1, @_); }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re (tilly) 2: Best/possible ways to dynamically use modules
by tilly (Archbishop) on Dec 18, 2001 at 10:20 UTC | |
by perrin (Chancellor) on Dec 18, 2001 at 21:43 UTC | |
by tilly (Archbishop) on Dec 18, 2001 at 21:52 UTC |
In Section
Seekers of Perl Wisdom