How can I require an optional Perl module if installed?
Here's a bare-bones solution that does not require another module:
my $rc = eval
{
require Term::ReadKey;
Term::ReadKey->import();
1;
};
if($rc)
{
# Term::ReadKey loaded and imported successfully
...
}
Note that all the answers below (I hope they're below this one! :-) that use eval { use SomeModule }
are wrong because use
statements are evaluated at compile time, regardless of where in the code they appear. So if SomeModule
is not available, the script will die immediately upon compiling.
(A string eval of a use
statement will also work (eval 'use SomeModule';
), but there's no sense parsing and compiling new code at runtime when the require
/import
pair does the same thing, and is syntax-checked at compile time to boot.)
Finally, note that my use of eval { ... }
and $@
here is succinct for the purpose of this example. In real code, you should use something like Try::Tiny, or at least be aware of the issues it addresses.
And if you require a specific version of the module:
my $GOT_READKEY;
BEGIN {
eval {
require Term::ReadKey;
Term::ReadKey->import();
$GOT_READKEY = 1 if $Term::ReadKey::VERSION >= 2.30;
};
}
# elsewhere in the code
if ($GOT_READKEY) {
# ...
}
The classic answer (dating back to Perl 4, at least, long before there was a 'use') was to 'require()' a module. This is executed as the script is run, rather than when compiled, and you can test for success or failure and react appropriately.
Check out the CPAN module Module::Load::Conditional. It will do what you want.