本文介绍了如何包含所有/部分“子模块"?在Perl脚本中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先要说的是,我对创建Perl模块完全没有经验,所以对不起,我很抱歉.

I'll just start out by saying I am not at all experienced with creating Perl modules so I'm sorry if I'm way off here.

假设我正在创建一些模块:

Let's say I am creating a few modules:

foo::bar
foo::bar::a
foo::bar::b

由于我不知道它们的名称,因此我将a.pm和b.pm模块称为子模块",因为它们与bar.pm模块相关,但仍可能是独立的.

Since I don't know what they are called, I am calling the a.pm and b.pm modules "sub modules" since they are related to the bar.pm module, but could still be somewhat independent.

所以我的一个Perl脚本可以使用foo :: bar :: a,另一个脚本可以使用foo :: bar :: b,也许我还有另一个脚本需要同时使用"a"和"b"中的函数".而不是这样说:

So one of my Perl scripts could use foo::bar::a, another script could use foo::bar::b, and maybe I have another script that needs to use functions from both "a" and "b". Instead of saying this:

use foo::bar;
use foo::bar::a qw(one two);
use foo::bar::b;

我想做这样的事情:

use foo::bar qw(:a :b);

在我看来,这将使我的脚本可以访问bar.pm,a.pm和b.pm中的所有内容.

In my mind, that would give my script access to everything in bar.pm, a.pm, and b.pm.

我测试了类似的东西,显然我错了.

I tested something like this, and I was obviously wrong.

像这样可能吗?我想我可以让bar.pm使用a.pm和b.pm,然后具有包装器"功能,将调用传递给子模块",但似乎会有一种更简单的方法.

Is something like this possible? I suppose I could have bar.pm use a.pm and b.pm, and then have "wrapper" functions that pass the call onto the "sub modules" but it seems like there would be an easier way.

推荐答案

看看我的测试: :Data 模块,以获取有关此操作的示例.即使您可以实现它,我也从未对结果感到非常满意.您可能想考虑使用插件"或混入"方法. CPAN 上有一些模块可以对此提供帮助.

Look at my Test::Data module for an example about doing that. Even though you can make it happen, I've never been terribly fond of the result. You might want to consider a Plugin or Mixin approach instead. There are some modules on CPAN that can help with this.

这是我为Test :: Data写的自定义import

Here's the custom import that I wrote for Test::Data:


sub import
    {
    my $self   = shift;
    my $caller = caller;

    foreach my $package ( @_ )
        {
        my $full_package = "Test::Data::$package";
        eval "require $full_package; 1";
        if( $@ )
            {
            carp "Could not require Test::Data::$package: $@";
            }

        $full_package->export($caller);
        }

    }

这篇关于如何包含所有/部分“子模块"?在Perl脚本中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:34