【问题标题】:Weirdness exporting constants created with enum::fields in perl在 perl 中使用 enum::fields 创建的奇怪导出常量
【发布时间】:2019-07-19 01:14:12
【问题描述】:

我创建了两个测试模块,X.pmX2.pmX.pm 模块有效。 X2.pm 模块没有,至少不像我期望的那样。

X.pm

package X {

    use enum::fields qw(I_VAL);
    use parent qw(Exporter);

    our @EXPORT = qw(I_VAL);
}

X2.pm

package X2 {

    our @EXPORT = qw(I2_VAL);

    use enum::fields (@EXPORT);
    use parent qw(Exporter);

}

测试程序是:

use X;
use X2;

printf("I_VAL = %d\n", I_VAL);
printf("I2_VAL = %d\n", I2_VAL);

输出是:

bash$ ./tmp/testit
I_VAL = 0
Undefined subroutine &X2::I2_VAL called at /home/bennett/tmp/testit line 15.

真正的项目有几十个enum::fieldsX2.pm是我尝试保持枚举与导出同步。

我的问题是:

  • 为什么X2 不起作用?之前是出口(进口)吗 enum::fields 跑了吗?
  • 我该怎么办?

【问题讨论】:

    标签: perl enums exporter


    【解决方案1】:

    Use 语句一编译就执行,所以

    use enum::fields (@EXPORT);
    

    之前执行
    our @EXPORT = qw(I2_VAL);
    

    这可行:

    package X3;
    
    use strict;
    use warnings;
    
    my @enum; BEGIN { @enum = qw( I2_VAL ); }
    
    use Exporter     qw( import );
    use enum::fields @enum;
    
    our @EXPORT = @enum;
    
    1;
    

    【讨论】:

    • 太棒了!这就像一个冠军。为什么?是不是因为在 use enum::fields 已经运行之后才执行分配?
    • 是的,所以@EXPORT 是空的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 2023-02-24
    • 2011-09-27
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多