Re: Writing a Perl module that dynamically loads other modulesby stephen (Priest)
|on Mar 01, 2013 at 20:17 UTC||Need Help??|
I'm assuming that you have some way of going from your file type to a module name (i.e. if the filetype is "foo" you load the "My::Module::Foo" module). I'm also assuming that you're not too worried about security, or that you're somehow validating these inputs.
You have a couple of choices for how to dynamically load a module based on the name.
Before we get into the technical aspect of how to do this, first we should consider *why* you want to do dynamic loading. If you have a manageable number of file formats, you can just 'use' them in your script (or put them all in the same file) and just call them when you need them. Something like:
One way is to use the Module::Load module from CPAN. That would let you do:
Alternatively, you can use 'require', like so:
If you can avoid the dynamic loading, I'd recommend doing so, and just 'use' the expected modules up front. That way you'll reduce complexity and see any errors at load-time. Also, it's a good idea to validate the module names somehow-- a typo in a format type will otherwise show up as a missing module error, and that can get confusing. Good luck!