try to use Module in Perl and print message if module not available

前端 未结 6 737
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 02:38

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.\"


        
相关标签:
6条回答
  • 2020-12-14 03:00

    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';
    
    0 讨论(0)
  • 2020-12-14 03:01

    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.";
    
    0 讨论(0)
  • 2020-12-14 03:08

    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';
    }
    
    0 讨论(0)
  • 2020-12-14 03:12
    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?

    0 讨论(0)
  • 2020-12-14 03:14

    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 $@;
    }
    
    0 讨论(0)
  • 2020-12-14 03:17

    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.

    0 讨论(0)
提交回复
热议问题