Perl: detect if a module is installed before using it

I wanted to check if a Perl module was installed at runtime, and error out accordingly if it wasn't. This allows me to print intelligent error messages if a module is not installed.

eval { require Weird::Module; };
if ($@) { die("Module is not installed\n"); }

This allows you to create runtime functions depending on which module is installed:

# Debug print variable using either Data::Dump::Color (preferred) or Data::Dumper
# Creates methods k() and kd() to print, and print & die respectively
BEGIN {
    if (eval { require Data::Dump::Color }) {
        *k = sub { Data::Dump::Color::dd(@_) };
    } else {
        require Data::Dumper;
        *k = sub { print Data::Dumper::Dumper(\@_) };
    }

    sub kd {
        k(@_);

        printf("Died at %2\$s line #%3\$s\n",caller());
        exit(15);
    }
}

Or you can use AUTOLOAD to only load the module if you actually call k()

sub AUTOLOAD { 
    our $AUTOLOAD; # keep 'use strict' happy

    if ($AUTOLOAD eq 'main::k' || $AUTOLOAD eq 'main::kd') {
        if (eval { require Data::Dump::Color }) {
            *k = sub { Data::Dump::Color::dd(@_) };
        } else {
            require Data::Dumper;
            *k = sub { print Data::Dumper::Dumper(@_) };
        }

        sub kd {
            k(@_);

            printf("Died at %2\$s line #%3\$s\n",caller());
            exit(15);
        }

        eval($AUTOLOAD . '(@_)');
    }
}

These functions should mimic some Krumo functionality.

Leave A Reply
All content licensed under the Creative Commons License