Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: use alternate module if pm is not installed

by haukex (Archbishop)
on Apr 07, 2021 at 09:15 UTC ( #11130940=note: print w/replies, xml ) Need Help??

in reply to use alternate module if pm is not installed

One way to do this is:

BEGIN { unless ( eval 'use DesiredModule; 1' ) { require AlternateModule; AlternateModule->import(); } }

However, I've also made the argument that using two different modules is not necessarily the best approach. There's ways to get modules onto systems where you don't have permissions (local::lib or even App::FatPacker), plus if you're going to be writing your own module anyway, why not just always use that?

Updates: Added the ->import call, as per choroba's post. It's often not required for OO modules. If you need to pass a specific import list, you can do eval 'use DesiredModule qw/some_func other_func/; 1' and AlternateModule->import(qw/some_func other_func/);. Another possible variation is that you can replace the inner block require ... ->import(); with eval 'use AlternateModule; 1' or die $@||'unknown error';. Stringy eval is often the wrong choice, but in this case it's fine because it's using a fixed string of code.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11130940]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2022-11-28 00:35 GMT
Find Nodes?
    Voting Booth?