I have Perl code which relies on Term::ReadKey to get the terminal width. My installation is missing this module, so I want to provide a default if the module isn’t present rather than throw an exception.
How can I conditionally use an optional module, without knowing ahead of time whether it is available.
# but only if the module is installed and exists use Term::ReadKey; ...
How can I accomplish this?
Here’s a bare-bones solution that does not require another module:
Note that all the answers below (I hope they’re below this one! 🙂 that use
eval { use SomeModule }are wrong becauseusestatements are evaluated at compile time, regardless of where in the code they appear. So ifSomeModuleis not available, the script will die immediately upon compiling.(A string eval of a
usestatement will also work (eval 'use SomeModule';), but there’s no sense parsing and compiling new code at runtime when therequire/importpair 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.