Dallaylaen
Dallaylaen

Reputation: 5308

Module::Load: Find out whether a module failed to load because of error, or simply doesn't exist

I want a module to dynamically load plugins using Module::Load. If there's no such plugin, it's OK, but if it is there and fails to load, I want to take action (e.g. give a warning, or even die).

A temporary solution looks like $@ !~ /^Couldn't locate /, however, I don't find it bullet-proof. E.g. a module may require another module which is absent, or use Module::Load itself, or etc.

The Module::Load itself isn't that complicated after all, so I was even considering adding a package variable there (e.g. $Module::Load::Absent), but I'm not sure it makes sense.

So, the question: how do I tell loading a missing module from loading a defective one?

Upvotes: 3

Views: 1271

Answers (3)

xenoterracide
xenoterracide

Reputation: 16837

You might want to use Module::Load::Conditional instead. It has the ability to check_install and check can_load so you can find out if your module is installed and simply can't load.

use Carp;
use Module::Load::Conditional;

if ( check_install( module =>  'Data::Dumper' ) ) {
    if ( can_load( modules => { 'Data::Dumper' => undef } ) ) { # any version of Data::Dumper
        requires 'Data::Dumper'; # load Data::Dumper part of ::Conditional
    }
    else {
       carp 'can\'t load Data::Dumper';
    }
}
else {
    carp 'Data::Dumper not installed';
}

Upvotes: 3

holygeek
holygeek

Reputation: 16185

To find out if there's no such plugin you can iterate through @INC and check if the file that is supposed to contain the module exists, something like the following (untested of course :):

use File::Spec::Functions;

my $filename = catfile(split('::', $modulename)) . '.pm';
foreach my $path (@INC) {
    if ( -f catfile($path, $filename)) {
       # found it!
       last;
    }
}

Upvotes: 0

Sauce
Sauce

Reputation: 1

I would try the following:

use Module::Load;

my $module = 'Data:Dumper';

if (load $module)
{
    # Success
}
else
{
    # Fail
}

Upvotes: 0

Related Questions