如何在Perl中实现延迟模块加载?
我在python中看到了类似的东西,实现有点简单,但在Perl中我认为这会有点困难.
解决方法
根据需要加载模块
如果需要在运行时加载整个模块,则使用require
.但是要导入,则需要额外的代码.这是一个例子:
- ## this function is almost the same
- ## as "use My::Module qw( :something )"
- sub load_big_module_at_runtime {
- ## load module in runtime
- require My::Module;
- ## do import explicty if you need it
- My::Module->import( ':something' );
- }
使用其功能时加载模块
您还可以在use autouse
仅在使用其功能时加载模块.例如:
- ## will load module when you call O_EXCL()
- use autouse Fcntl => qw( O_EXCL() );
仅在使用时加载功能
还有SelfLoader
模块,它允许您仅在需要时加载单个功能.看看@L_403_4@模块,它做了几乎相同的事情.
我还建议从Perl Cookbook阅读相应的食谱.