【问题标题】:perl: Exporter doesn't work with path elements in the `use` statementperl:Exporter 不适用于 `use` 语句中的路径元素
【发布时间】:2012-06-22 08:51:35
【问题描述】:

我有一个 perl 问题:导入符号,这取决于 @INCuse 语句中的路径元素。

如果我将完整路径放入@INC,则导入工作。如果路径的一部分在 use 语句中,则执行要导入的模块,但必须显式完成导入:

########################################
# @INC has: "D:/plu/lib/"

#------------------------------------------------
# Exporting file is here: "D:/plu/lib/impex/ex.pm"
#
use strict;
use warnings;
package ex;

use Exporter;
our @ISA = 'Exporter';
our @EXPORT = qw( fnQuark );

sub fnQuark { print "functional quark\n"; }

print "Executing module 'ex'\n";
1;

#------------------------------------------------
# Importing file, example 1, is here: "D:/plu/lib/impex/imp.pl"
#
use strict;
use warnings;
package imp;

use impex::ex;

ex->import( @ex::EXPORT );    # removing this line makes fnQuark unavailable!
                              # Why is this necessary, 'ex.pm' being an Exporter?
fnQuark();

#------------------------------------------------
#  Importing file, example 2, is here: "D:/plu/lib/impex/imp2.pl"
#
use strict;
use warnings;
package imp2;

use lib 'D:/plu/lib/impex';
use ex;

fnQuark();                    # works without explicit import
#-------------------------------------------------

我的错误是什么?

【问题讨论】:

    标签: perl exporter


    【解决方案1】:

    当你说

    use Foo;
    

    这相当于:

    BEGIN { 
        require 'Foo.pm';
        Foo->import;
    };
    

    你已经在你的ex.pm 中定义了包命名为ex,所以当你use impex::ex 时,Perl 执行一个隐含的impex::ex->import。但是没有名为impex::ex 的包,因此您必须手动从ex 导入才能获取符号。

    执行此操作的正确方法是将模块放在@INC 中的现有目录下,并以相对于@INC 目录的完整路径名命名包。所以你的impex/ex.pm应该以package impex::ex;开头,这就是你应该use它的方式。

    如果您担心软件包名称冗长且笨拙,请查看aliased

    【讨论】:

    • 感谢您的快速回复。但我不明白为什么我以前没有这个问题。我有很多模块,例如。 G。 lib/Foto 中的“FotoArchive.pm”,包名 FotoArchive 和 Foto 不在 @INC 路径中。为什么当我通过 Foto::FotoArchive 调用它们时不会导致同样的问题? ——啊,我开始明白了,因为他们不出口任何东西。所以我逃脱了我的错误被忽视了这么久!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多