try to use Module in Perl and print message if mod

2019-01-22 07:54发布

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?

6条回答
该账号已被封号
2楼-- · 2019-01-22 08:36

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';
查看更多
放荡不羁爱自由
3楼-- · 2019-01-22 08:38
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?

查看更多
不美不萌又怎样
4楼-- · 2019-01-22 08:39

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.";
查看更多
孤傲高冷的网名
5楼-- · 2019-01-22 08:40

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';
}
查看更多
走好不送
6楼-- · 2019-01-22 08:41

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 $@;
}
查看更多
小情绪 Triste *
7楼-- · 2019-01-22 08:55

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.

查看更多
登录 后发表回答