【问题标题】:perl constant definition in a dedicated package专用包中的 perl 常量定义
【发布时间】:2011-07-30 01:32:53
【问题描述】:

我想为主要 perl 程序和其他包的所有常见声明设置一个专用包,而不在每个标题中重复这些声明。我肯定弄错了,但无法弄清楚背后的原因:

让我们假设:
- 我已经在 my_common_declarations.pm 包中设置了我的通用数据。
- 我想在另一个包中使用这些数据,例如 my_perl_utils.pm

#!/usr/bin/perl -w
package my_perl_utils;
use parent qw(Exporter);
our @EXPORT_OK = qw(f1 f2);
use my_common_declarations qw(debugme);
my %setup = &debugme;
my $DEBUGME = $setup{setup}{debugme};

# This generates this error : "Use of uninitialized value"
use constant true => $setup{setup}{'true'};
print "=" x25, "\nDEBUG true :\nimport = " . $setup{setup}{'true'} . "\nconstant = " , true , "\n", "=" x25, "\n"; 

sub f1{
# some rationals using the true or false constants
}

sub f2{
}

1;  

我无法成功声明没有错误的“真实”常量。

我应该在主程序中只导入一次通用声明包并在其中相应地声明常量,还是在我需要此常量的每个包中重新声明它?

谢谢

【问题讨论】:

    标签: perl constants package declaration shared


    【解决方案1】:

    您遇到的问题是脚本中运行时和编译时之间的交互。任何use 声明都有一个隐含的BEGIN {...} 块,这意味着它发生在编译时。您对 %setup 的赋值发生在运行时,在声明常量之后。解决此问题的方法是声明变量,然后在 BEGIN 块中对其进行赋值。这样,变量将在调用use constant ... 时定义:

    use my_common_declarations 'debugme';
    
    my (%setup, $DEBUGME);  # declare variables with file scope
    
    BEGIN {
        %setup   = debugme;                # assign to variables at compile time
        $DEBUGME = $setup{setup}{debugme};
    }
    
    use constant true => $setup{setup}{true}; # %setup is defined now
    

    另外,既然您要导出一个返回哈希的函数,为什么不让它返回一个哈希引用,那么您可以将代码编写为:

    use my_common_declarations 'debugme';
    
    use constant true => debugme->{setup}{true};
    

    在这种情况下,由于debugme 是在编译时由第一条use 语句导入的,所以它在use constant ... 行中可用。

    但是,既然您要声明一个用于通用声明的包,为什么不将常量定义移到该包中,然后将 true 之类的内容添加到该包的导出列表中?

    【讨论】:

    • thx 我会仔细查看您的 cmets 并尝试实施。
    • 但是他也在包名中使用了下划线,这意味着它是为本地使用而保留的(就像他正在做的那样)。详情请见this question
    • @cjm => 感谢您指出这一点,我已经删除了我答案的那部分。
    • 我确实按照建议将常量的定义移到了包中,好多了,谢谢。还有this 帮助。
    猜你喜欢
    • 1970-01-01
    • 2010-11-29
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多