开发者

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

开发者 https://www.devze.com 2023-03-25 08:48 出处:网络
I want a module to dynamically load plugins using Module::Load. If there\'s no such plugin, it\'s OK, bu开发者_C百科t if it is there and fails to load, I want to take action (e.g. give a warning, or e

I want a module to dynamically load plugins using Module::Load. If there's no such plugin, it's OK, bu开发者_C百科t 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?


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';
}


I would try the following:

use Module::Load;

my $module = 'Data:Dumper';

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


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消