Home » How To » Perl: How to check that the Perl Modules are installed at runtime

Perl: How to check that the Perl Modules are installed at runtime

Often when you write a Perlprogram in Perl, you know which system(s) you’re going to be using the program on and you can ensure the required Perl modules are installed. Other times, you may not. Unless you want to be called simply because a required Perl module wasn’t installed on a system, you probably should check and provide a meaningful error message.

In this example, we’ll use the core module Module::Load in order to load a module. We also declare the %MISSING_MODULE hash:

use Module::Load;

our %MISSING_MODULE;

We populate the %noncore_modules with non-core modules we want to use. If the value for the module is an array, we will import those specific variables/subroutines:

BEGIN {
    # We're going to use:
    #   Pod::Usage with no special imports
    #   My::Secret::Module importing *ONLY* potato and carrot subroutines
    my %noncore_modules = (
        'Pod::Usage'         => 'default',
        'My::Secret::Module' => [ qw(
            potato
            carrot
            ) ],
    );

    foreach my $tmp_module (keys %noncore_modules ) { 
        if (eval { load $tmp_module ; 1; } ) { 
            if ( ref( $noncore_modules{$tmp_module} ) eq 'ARRAY' ) { 
                # Only specified subroutines/variables specified in
                #  %noncore_modules will be imported
                $tmp_module->import( @{ $noncore_modules{$tmp_module} } );
            } else {
                # anything in the @EXPORT of the module will be imported
                #  @EXPORT_OK will not be imported

                $tmp_module->import();
            }   
        } else {
            $MISSING_MODULE{$tmp_module} = 1;
        }   
    }
}

Now that we’ve loaded Perl modules that we could, let’s report on any that failed to load:

if (%MISSING_MODULE) {                                            
    $RC = 1;

    foreach my $perl_module (keys %MISSING_MODULE) {
        printf STDERR "Missing Perl module %s. Please have unix team install the module and verify permissions!\n", $perl_module;
        print STDERR "ABORTING\n";
    }

    exit $RC;
}
Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

Facebook login by WP-FB-AutoConnect