tags:

views:

634

answers:

4

Hi,

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?

+8  A: 

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.

Chas. Owens
the use from your last code statement should start with a lowercase u,right?
Geo
Yeah, I fixed it and added a link Module::Load's CPAN entry
Chas. Owens
Require is fatal on errors, so it must be wrapped in an eval. Also, to be identical to 'use' any require/import code must be in a BEGIN block. So: BEGIN { eval {require 'Module' or die "Ugh."; Module->import; 1 } or do{ die "You lack Module" } }
daotoad
+7  A: 

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';
}
Pierre-Luc Simard
A: 
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?

Ether
It's useful to avoid the app/script dying when the module is used for some optional feature.
Lars Haugseth
A: 

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