【问题标题】:Perl: How to use constant defined in other pl file from a strict perl file?Perl:如何使用严格的 perl 文件中其他 pl 文件中定义的常量?
【发布时间】:2020-12-15 10:16:52
【问题描述】:

我们有一些 perl 文件处于严格模式,而有些则没有。一些常量(全局变量)在 perl 库 (.pl) 中以非严格模式定义,例如 "$XXXX = '....';" .

当我尝试在严格模式下处理 perl 文件以使用此类常量/全局变量(在非严格模式 perl 文件中定义)时,出现编译错误“全局符号“$XXXX”需要显式包名” .

我对 perl 有点陌生。到目前为止,在我看来,包仅在 perl 模块 (.pm) 中可用,我无法将包添加到 perl 库 (.pl) 文件中,对吗?

我想最好的方法是将所有常量放在一个模块中,但这需要更改所有使用常量的文件。现在我们更喜欢最小数量的文件更改。我想知道是否有其他方法可以在保持原始严格或非严格模式的同时解决它?

【问题讨论】:

    标签: perl


    【解决方案1】:

    这(部分)是 Exporter 的用途。

    MyConsts.pm:

    package MyConsts;
    
    use strict;
    use warnings;
    
    # Load the Exporter module
    use parent 'Exporter';
    
    # Define the symbols that will be exported
    our @EXPORT = qw($Important_Constant);
    
    # Declare and set the variables.
    # Note that they must be *package* variables
    # (so use "our", not "my")
    our $Important_Constant = 10;
    
    1;
    

    在程序中:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use feature 'say';
    
    use MyConsts;
    
    say $Important_Constant;
    

    【讨论】:

    • 不错的答案。但是你的意思是说在 MyConsts.pm:(在.pm 之前加上一个s),对吗?
    • @J-L,是的,已修复。
    猜你喜欢
    • 2010-11-29
    • 2019-04-30
    • 2011-02-07
    • 1970-01-01
    • 2011-07-30
    • 2013-06-29
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多