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 Dump::Krumo }) {
        Dump::Krumo->import(qw/k kd/);
    } else {
        require Data::Dumper;
        *k  = sub { print Data::Dumper::Dumper(\@_) };
        *kd = sub { print Data::Dumper::Dumper(\@_); die; };
    }
}

These functions should mimic some Krumo functionality.

Tags:
Leave A Reply
All content licensed under the Creative Commons License