petersohn
petersohn

Reputation: 11730

How can I conditionally import a package in Perl?

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;
}

Upvotes: 3

Views: 1181

Answers (4)

daxim
daxim

Reputation: 39158

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

Edit: disregard the comments, Module::Load is in core.

Upvotes: 2

mfollett
mfollett

Reputation: 1814

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.

Upvotes: 0

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118128

Consider the if pragma.

use if CONDITION, MODULE => ARGUMENTS;

Upvotes: 4

Eugene Yarmash
Eugene Yarmash

Reputation: 149786

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.

Upvotes: 6

Related Questions