Matteo
Matteo

Reputation: 14930

Perl: Fallback to an older Module

I have several Nagios plugins that were using Nagios::Plugin. The module is now deprecated and was substituted by Monitoring::Plugin.

As several distributions are not updated yet I check in the code which module is available

sub load_module {

    my @names = @_;
    my $loaded_module;

    for my $name (@names) {

        my $file = $name;

        # requires need either a bare word or a file name
        $file =~ s{::}{/}gsxm;
        $file .= '.pm';

        eval {
            require $file;
            $name->import();
        };
        if ( !$EVAL_ERROR ) {
            $loaded_module = $name;
            last;
        }
    }

    if ( !$loaded_module ) {
        # handle error ...
        exit 2;
    }

    return $loaded_module;

}

my $plugin_module = load_module( 'Monitoring::Plugin', 'Nagios::Plugin' );
my $plugin_threshold_module = load_module( 'Monitoring::Plugin::Threshold', 'Nagios::Plugin::Threshold' );

I used to check for the module availability in a Makefile.PL file with

requires 'Nagios::Plugin'            => 0;
requires 'Nagios::Plugin::Threshold' => 0;

and the use the module in my plugin.

Is there a standard way in Makefile.PL to check for a module (i.e., Monitoring::Plugins) and if not available check if another option is available (i.e., Nagios::Plugin::)?

Upvotes: 1

Views: 214

Answers (1)

Schwern
Schwern

Reputation: 164899

The Makefile.PL is just a program, you can do the same check you're doing at runtime.

my %prereqs = (
    ...declare your static prereqs...
);

if( eval { require Monitoring::Plugin } ) {
    $prereqs{'Monitoring::Plugin'};
}
else {
    $prereqs{'Nagios::Plugin'};
}

WriteMakefile(
    ...blah blah blah...

    PREREQ_PM => \%prereqs
);

Other module build systems such as Module::Install and Dist::Zilla may support plugins to do that for you, but the basic result will be the same.

Note that this will generate a META file for your distribution describing your prerequisites. It will not have this logic and instead will show your module requiring whatever the outcome was at the time you built your distribution, there is no means in the spec to express what you want. This will not break anything, CPAN module installers will run the Makefile.PL and trust what it says over the META file so long as dynamic_config is true (which it is by default). However, the dynamic nature of your requirements will not be shown on things like https://metacpan.org.

Upvotes: 1

Related Questions