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

两盒软妹~` 提交于 2021-01-28 06:12:35

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!