我应该将两个 Perl 模块共有的代码放在哪里?
我正在创建几个 Perl 模块,它们将使用常用实用程序来打开和关闭文件。
例如,
mod1.pm
my $in, $out;
sub openf {
my $fname = shift;
open $in, "<", $fname or die $!;
}
sub one {
openf($path);
...
}
mod2.pm
my $in, $out;
sub openf {
my $fname = shift;
open $in, "<", $fname or die $!;
}
sub two {
openf($path);
...
}
现在,我应该将 openf
放在哪里才能使代码不重复?
I am creating several Perl modules which will use the common utilities for opening and closing files.
For example,
mod1.pm
my $in, $out;
sub openf {
my $fname = shift;
open $in, "<", $fname or die $!;
}
sub one {
openf($path);
...
}
mod2.pm
my $in, $out;
sub openf {
my $fname = shift;
open $in, "<", $fname or die $!;
}
sub two {
openf($path);
...
}
Now, where should I put openf
so that the code is not duplicated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会说采用最简单的解决方案。
创建第三个模块,Common.pm 或 Helpers.pm 或 MyUtils.pm - 在那里存储所有常见的样板帮助程序子例程。
然后,您将从上面的两个模块以及其他任何地方导入它。
一种稍微不同的方法是 - 而不是简单地
使用
-ing Common.pm - 实际上继承其中的所有模块。这样他们就可以按照 OO 方式根据需要扩展通用实用程序。我们实际上在一个大型项目中做到了这一点,从 BaseClass.pm 或 BaseClassPlus.pm(它的子类)中对几乎 100% 的模块进行了子类化。工作得很好,并且由于样板代码显着减少,因此非常有利于维护良好的代码。 (我有一种感觉,我们可以用 Moose 完成大部分工作,但那是在我知道 Moose 存在之前)
I'd say go with the simplest solution.
Make a 3rd module, Common.pm or Helpers.pm or MyUtils.pm - store all the common boilerplate helper subroutines there.
You will then import it from both of the modules above as well as anywhere else.
A slightly different approach is - instead of simply
use
-ing Commmon.pm - to actually inherit all your modules from it. That way they can extend the common utils as needed in OO fashion.We actually did that with a large project, sub-classing almost 100% of modules from either BaseClass.pm or BaseClassPlus.pm which was its subclass. Worked very well and was very conductive to well-maintainable code due to significantly less boilerplate. (I have a feeling we could have done a large part of the work with Moose but that was before I even knew Moose existed)