How can I conditionally import a package into Perl?

I have a Perl script that uses a not very general module, and I want it to be available without a module installed, albeit 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;
}
+3
source share
4 answers

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

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

See also perldoc use .

+6
source

Consider if pragma.

use if CONDITION, MODULE => ARGUMENTS;
+4
source
+2
source

Another approach is to use the :: MOP load_class class method. You can use it like:

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

It throws an exception, so you have to catch it. More details here .

In addition, although this is not necessary for every system, the :: MOP class is extremely useful, and with Moose it is becoming more common every day, probably on your system.

0
source

Source: https://habr.com/ru/post/1770059/


All Articles