Announcing Module::UseFrom

So what do you do when you need to load a module from a string? Do you do eval "require $module"? Well as many of you may have read, that is How (not) to Load a Module. This mechanism is unsafe in certain situations, but sadly there hasn’t been a good answer for it.

What do you do when you want to load a module only if it is installed, or only if it is of a certain version or higher (without dieing). Of course there are eval ways around that too, but could they be easier?

This post announces Module::UseFrom, which lets you do all of these things. But it gets better! All of these actions are done using the much safer bareword form of use, accomplishes this at compile time, and does it without any evals[1]!

It does all this using Devel::Declare to inspect a package variable in your module and inject a bareword use statement. This means that it avoid most (all?) of the problems Schwern’s post (above); if it fails to create the right statement, perl (yes lowercase) dies on the use Bareword::Module statement.

Check it out, fork, comment etc. https://github.com/jberger/Module-UseFrom

Happy New Year everyone!

[1]: ok, there is a s///e, but its for convenience, and its safe.

3 Comments

Joel asked for my commentary, so here it is.

Pro: Using Devel::Declare to get around the problems of loading a module dynamically is a very clever solution…

Con: …but it severely restricts the utility of the module. It can only be used when you know what you’re loading at compile time.

Other: The basic use_from is fine, but extras are tacked on to avoid writing use_from more than once. They gum up the interface. They cause use_from to diverge from the known use interface. More for the user to read and get confused about. More opportunities for bugs and security holes. I would simply remove them. The only actual extra functionality is check_installed which should be its own function. use_if_installed or something.

In conclusion, if you happen to need to load modules dynamically and at compile time, this is the module for you.

Leave a comment

About Joel Berger

user-pic As I delve into the deeper Perl magic I like to share what I can.