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, @_); }
In reply to Re: Best/possible ways to dynamically use modules
by chipmunk
in thread Best/possible ways to dynamically use modules
by pdt1630
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |