问题
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 warn
s Dumping an object if Data::Dumper
is available or otherwise just warn
s, how can I do that?
回答1:
BEGIN {
if (eval { require Data::Dumper }) {
*dumper = sub { warn(Data::Dumper::Dumper(@_)) };
} else {
*dumper = sub { };
}
}
dumper(...);
The downside of the above is that expensive expressions passed as arguments still need to be calculated if Data::Dumper isn't available.
use constant has_dumper => eval { require Data::Dumper };
BEGIN {
if (has_dump) {
*dumper = sub { warn(Data::Dumper::Dumper(@_)) };
} else {
*dumper = sub { };
}
}
dumper(...); # Ok
dumper(...) if has_dumper; # Statement completely optimized away if DD missing.
回答2:
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 );
}
来源:https://stackoverflow.com/questions/64918978/how-can-i-write-code-that-optionally-uses-a-module-if-it-exists