Search code examples
perlmodulerequire

How can I write code that optionally uses a module if it exists?


If I want to write code that optionally uses a module how can I do it? For example, if I want to write code that warns Dumping an object if Data::Dumper is available or otherwise just warns, how can I do that?


Solution

  • This is an effective idiom for loading an optional module,

    use constant has_Module => defined eval { require Module };
    

    This will require the module if available, and store the status in a constant.

    You can use this like,

    use constant has_DataDumper => defined eval { require Data::Dumper };
    
    warn "got object";
    if ( has_DataDumper ) {
      warn Data::Dumper::Dumper( $obj );
    }