Perl 命名空间问题 : using exported functions in modules not working

标签 perl

我在一个小的 Perl 模块中打包了一些常用函数,我在脚本中使用

use lib path/to/lib

在模块文件中,我导入了一些其他系统安装的模块(例如 Carp qw(confess) ,但我不能直接调用 confess,而是调用 Carp::confess ,这对我来说很不寻常。

这是我的(非)工作示例:
https://github.com/telatin/bioinfo/blob/master/mini/script.pl
use 5.012;
use FindBin qw($Bin);
use lib "$Bin/Demo/lib";
use Local::Module;

say "Version: ", $Local::Module::VERSION;

Local::Module->new();

模块:https://github.com/telatin/bioinfo/blob/master/mini/Demo/lib/Local/Module.pm
use 5.012;
use warnings;
use Carp qw(confess);
package Local::Module;
$Local::Module::VERSION = 2;


sub new {
    my ($class, $args) = @_;
    my $self = {
        debug   => $args->{debug}, 
    };
    my $object = bless $self, $class;

    confess "Unable to create fake object";
    return $object;
}

1;

我应该在 .pm 文件中做什么来避免这个问题?

最佳答案

问题在这里:

use 5.012;
use warnings;
use Carp qw(confess);
package Local::Module;

首先加载Carp并导入 confess ,但此时您仍在包中 main , 所以 confess被导入 main .

然后你用 package Local::Module 切换包,但没有 confess这里定义的函数。

您需要先切换包:
package Local::Module;
use 5.012;
use warnings;
use Carp qw(confess);

现在所有导入和所有以下代码都在同一个包中。

关于Perl 命名空间问题 : using exported functions in modules not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56904393/

相关文章:

algorithm - 这个算法有名字吗?

perl - 什么时候应该使用子程序属性?

python - "Real"和非嵌入式使用 Ruby、Python 和他们的 friend

java - 无法在 Windows 框中安装 WWW::HtmlUnit

perl - 从日志尾部提取匹配行后退出

perl - 构建发行版后,两个单独的 META 文件的目的是什么?

regex - 不匹配 [ 在正则表达式中,尽管被转义

perl - 在文本文件中编辑/分割/保存数据

Perl:检查是否设置了环境变量

regex - Perl 条件替换