try to use Module in Perl and print message if mod

2019-01-22 07:59发布

问题:

I wanted to be able to do this in Perl (the code below is Python lol)

try:
  import Module
except:
  print "You need module Module to run this program."

Does anyone have any idea how to?

回答1:

TIMTOWTDI:

eval "use Module; 1" or die "you need Module to run this program".

or

require Module or die "you need Module to run this program";
Module->import;

or

use Module::Load;

eval { load Module; 1 } or die "you need Module to run this program";

You can find Module::Load on CPAN.



回答2:

You can use Module::Load::Conditional

use Module::Load::Conditional qw[can_load check_install requires];


my $use_list = {
    CPANPLUS     => 0.05,
    LWP          => 5.60,
    'Test::More' => undef,
};

if(can_load( modules => $use_list )) 
{
   print 'all modules loaded successfully';
} 
else 
{
   print 'failed to load required modules';
}


回答3:

There are many modules for doing that; see the list of CPAN modules that (can) load other modules. However, it is a bit risky to rely on an external module (what if it is not present?). Well, at least, if you rely on Moose, Class::Load can be used safely as it is Moose's prerequisite:

#!/usr/bin/env perl
use strict;
use utf8;
use warnings qw(all);

use Class::Load qw(try_load_class);

try_load_class('Module')
    or die "You need module Module to run this program.";


回答4:

Something like this, use Net::SMTP if you have the module installed, or a cheesy sendmail callout as a last resort.

my $mailmethod = eval "use Net::SMTP; 1" ? 'perl' : 'sendmail';


回答5:

use strict;
use warnings;
use Module;

If you don't have Module installed, you will get the error "Can't locate Module.pm in @INC (@INC contains: ...)." which is understandable enough.

Is there some particular reason you want/need a more specific message?



回答6:

Here's how I'm going about it:

sub do_optional_thing {
    init_special_support();
    Module::Special::wow();
}

sub init_special_support {
    # check whether module is already loaded
    return if defined $INC{'Module/Special'};

    eval {
        require Module::Special;
        Module::Special->import();
    };

    croak "Special feature not supported: Module::Special not available" if $@;
}