perl - 如何使用 "use strict"导入常量,避免 "Can' t 使用 bareword ... 作为 ARRAY ref"

标签 perl import module reference constants

我在一个文件中有一个模块,它导出一个作为数组引用的常量。我可以在其定义模块中使用该常量,但在导入后我无法使用它。错误消息显示 Can't use bareword ("AR") as an ARRAY ref while "strict refs" in use at mod.pl line 28. .

考虑这个演示代码:

#!/usr/bin/perl
require 5.018_000;

use warnings;
use strict;

package Test;

use warnings;
use strict;

BEGIN {
    require Exporter;
    our $VERSION = 1.00;                # for version checking
    # Inherit from Exporter to export functions and variables
    our @ISA = qw(Exporter);
    our @EXPORT = qw();                 # exported by default
    our @EXPORT_OK = qw(AR);            # can be optionally exported
}

use constant AR => [1,2,3];

print AR->[1], "\n";
1;

package main;
Test->import(qw(AR));
print AR->[1], "\n";
#Can't use bareword ("AR") as an ARRAY ref while "strict refs" in use at mod.pl line 28.

我该如何解决?

最佳答案

您需要执行 import在编译对常量的引用之前。

您可以使用另一个 BEGIN阻止这样做,但这意味着我们现在有两个黑客。我建议采用以下方法,而不是同时对模块的用户和模块本身进行弗兰肯斯坦。它使内联包看起来尽可能像一个真正的模块。

该方法包括以下内容:

  • 将整个模块按原样放置在 BEGIN 中 block 在脚本的开头。
  • 替换尾随 1;$INC{"Foo/Bar.pm"} = 1; (对于 Foo::Bar)。

  • 就是这样。这使您可以 use模块正常。

    因此,如果您的模块如下:
    package Test;
    
    use strict;
    use warnings;
    
    use Exporter qw( import );
    
    our $VERSION = 1.00;
    our @EXPORT_OK = qw(AR);
    
    use constant AR => [1,2,3];
    
    1;
    

    如果您的脚本如下:
    #!/usr/bin/perl
    use 5.018;
    use warnings;
    
    use Test qw( AR );
    
    say AR->[1];
    

    您可以使用以下内容:
    #!/usr/bin/perl
    
    BEGIN {
        package Test;
    
        use strict;
        use warnings;
    
        use Exporter qw( import );
    
        our $VERSION = 1.00;
        our @EXPORT_OK = qw(AR);
    
        use constant AR => [1,2,3];
    
        $INC{__PACKAGE__ .'.pm'} = 1;  # Tell Perl the module is already loaded.
    }
    
    use 5.018;
    use warnings;
    
    use Test qw( AR );
    
    say AR->[1];
    

    如您所见,我进行了一些清理工作。具体来说,
  • 如果你需要 5.18,不妨启用它提供的语言功能。这是通过替换 required 5.018; 来完成的。与 use 5.018;
  • 我们不需要使用 use strict;明确地因为 use 5.012;和更高的启用限制。
  • 我们可以使用say因为use 5.010;启用它。
  • 测试不是导出器,所以它不应该从导出器继承。在过去的 15 到 20 年中,Exporter 一直提供比您使用的界面更好的界面。
  • 无需创建或初始化@EXPORT如果你不需要它。
  • 无需BEGIN阻止 @ISA 的初始化和 @EXPORT_OK .
  • 关于perl - 如何使用 "use strict"导入常量,避免 "Can' t 使用 bareword ... 作为 ARRAY ref",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55046430/

    相关文章:

    arrays - perl 比较数组元素并分组

    ruby-on-rails - 导入具有 55 行 Roo 的 csv 会导致 ActionDispatch::Cookies::CookieOverflow

    Python:如何从目录中的所有模块导入?

    perl - 使用 cpan 安装 Params::Validate - 无法启动 'Build'

    mysql - Perl, SQL, DBI : Why doesn't my UPDATE function work? 代码和我在里面尝试过的东西

    javascript - 从另一个模块导出模块类

    c# - 如何从 PRISM 中的区域获取 View ?

    perl - 如何将通用参数传递给 Perl 模块?

    json - 如何在 Perl 中验证 JSON?

    yii 导入目录分隔符