Perl:如何在许多独立脚本之间共享大量模块的导入? [英] Perl: how to share the import of a large list of modules between many independent scripts?
问题描述
我有很多独立脚本.它们唯一共享的是,它们使用()大量的CPAN模块(每个模块都导出多个功能).我想集中列出这些模块.我发现了几种方法.哪一个最好?
I have many standalone scripts. The only thing they share, is that they use() a large set of CPAN modules (that each export several functions). I would like to centralize this list of modules. I found several methods. Which one is the best?
-
我可以创建SharedModules.pm来导入所有内容,然后使用Exporter将所有内容手动导出到main ::.
I could create SharedModules.pm that imports everything and then manually exports everything to main:: using Exporter.
我可以创建以"package main;"开头的SharedModules.pm.因此它将直接导入main ::.看来行得通.这是不好的做法吗?为什么?
I could create SharedModules.pm that starts with "package main;" so it will import directly into main::. It seems to work. Is it bad practice and why?
我可能需要()一个sharedmodules.pl,似乎也将所有内容导入到main ::中.我不喜欢这种方法,因为require()在mod_perl下无法正常工作.
I could require() a sharedmodules.pl that seems to import everything into main:: as well. I don't like this method as require() doesn't work that well under mod_perl.
第二个对我来说看起来最好,但是我想知道为什么Modern :: Perl不能那样工作.
Number two looks best to me, however I wonder why for example Modern::Perl doesn't work that way.
I figured this question has been asked before.
推荐答案
您提出的所有三种解决方案的问题是,该模块可能是从另一个模块中use
d的,在这种情况下,应将符号导出到use
正在添加模块的软件包,而不是放入main
.
The problem with all three of your proposed solutions is that the module may be use
d from another module, in which case the symbols should be exported into the use
ing module's package, not into main
.
bvr使用caller
直接将内容导入该程序包的解决方案是朝正确方向迈出的重要一步,但阻止了真实"程序包使用use ShareableModules qw( foo bar baz);
仅选择性地导入其实际需要的内容.
bvr's solution of using caller
to import things directly into that package is a major step in the right direction, but prevents the 'real' package from using use ShareableModules qw( foo bar baz);
to selectively import only what it actually needs.
不幸的是,要保留选择性导入的能力,将需要您从基础模块中导入所有相关符号,然后从ShareableModules中重新导出它们.您不能仅将导入委派给每个基础模块的import
方法(如Modern::Perl
一样),因为如果import
要求输入不由该模块导出的符号,则会死掉.但是,如果这不是问题,那么Modern::Perl
的处理方式可能是最干净,最简单的选择.
Unfortunately, preserving the ability to import selectively will require you to import all relevant symbols from the underlying modules and then re-export them from ShareableModules. You can't just delegate the import to each underlying module's import
method (as Modern::Perl
does) because import
dies if it's asked for a symbol that isn't exported by that module. If that's not an issue, though, then Modern::Perl
's way of doing it is probably the cleanest and simplest option.
这篇关于Perl:如何在许多独立脚本之间共享大量模块的导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!