[sf-perl] dynamic use command

Joe Brenner doom at kzsu.stanford.edu
Fri Apr 4 11:42:02 PDT 2008

Michael Friedman <friedman at highwire.stanford.edu> wrote:

> The other thing you can do is realize that, according to `perldoc -f
> use`:
> 	It [use] is exactly equivalent to
>        	BEGIN { require Module; import Module LIST; }
> So you can put the require & import inside a conditional and get the
> same effect. I've chosen to use this construction for dynamic module
> loading:
> if ($needs_feature) {
> 	require Feature::Module;
> 	Feature::Module->import();
> }
> This does the same thing as 'use', but avoids the automatic BEGIN block.

Yes, this is the way I tend to do it as well (for example, in the
"Module::List::Pluggable" module out on CPAN [1]).

But I tend to combine this with the string-eval tricks other people
have been discussing:

  eval "require $module; import $module;";

Note that this is one of the few cases where you have to use the
string form of eval (usually the block form is recommended).  This
is explained a little better in the documentation for "require"
than it is for "use" (the jargon is that the argument must be a

  perldoc -f require

[1] I looked at Module::Pluggable, but I thought it's interface
was terrible, so I wrote my own.  Then I found out that
Module::Pluggable had made it into the core library for 5.10.

More information about the SanFrancisco-pm mailing list