views:

83

answers:

4

I have a Perl script which uses a not-so-common module, and I want it to be usable without that module being installed, although with limited functionality. Is it possible?

I thought of something like this:

my $has_foobar;
if (has_module "foobar") {
    << use it >>
    $has_foobar = true;
} else {
    print STDERR "Warning: foobar not found. Not using it.\n";
    $has_foobar = false;
}
+6  A: 

You can use require to load modules at runtime, and eval to trap possible exceptions:

eval {
    require Foobar;
    Foobar->import();
};  
if ($@) {
    warn "Error including Foobar: $@";
}

See also perldoc use.

eugene y
If you're going to call `import`, then you probably want to wrap this in a `BEGIN` block so it'll happen at compile time. Otherwise, `import` isn't likely to be useful.
cjm
A: 

I recommend employing Module::Load so that the intention is made clear.

daxim
The problem with this is that Module::Load is also something that is not instaled on every system.
petersohn
It's not a problem. [Declare the dependency](http://search.cpan.org/CPAN::Meta::Spec#prereqs), CPAN automatically takes care to install it before your module/program.
daxim
@daxim - this is an excellent suggestion for environments where you (the developer) have full control. Some environments are not like that (e.g. large company where Perl libraries are only allowed to be instealled on a software engineering controlled location and must be vetted by that team).
DVK
@DVK: Yes, that's exactly my problem.
petersohn
+3  A: 

Consider the if pragma.

use if CONDITION, MODULE => ARGUMENTS;
Sinan Ünür
A: 

Another approach is to use Class::MOP's load_class method. You can use it like:

Class::MOP::load_class( 'foobar', $some_options )

It throws an exception so you'll have to catch that. More info here.

Also, while this isn't necessarily on every system Class::MOP is awfully useful to have and with Moose becoming more prevalent every day it likely is on your system.

mfollett