我们有一些处于严格模式的 Perl 文件,有些则没有。一些常量(全局变量)在 Perl 库 (.pl) 中以非严格模式定义,例如 "$XXXX = '....';" .
当我尝试在严格模式下处理 perl 文件以使用此类常量/全局变量(在非严格模式 perl 文件中定义)时,出现编译错误“全局符号“$XXXX”需要显式包名称” .
我对 Perl 有点陌生。到目前为止,在我看来,该包仅在 perl 模块 (.pm) 中可用,并且我无法将包添加到 perl 库 (.pl) 文件中,对吗?
我想最好的方法是将所有常量放在一个模块中,但这需要更改所有使用常量的文件。现在我们更喜欢最少数量的文件更改。我想知道是否有其他方法可以解决这个问题,同时保持原来的严格或非严格模式?
最佳答案
这(部分)是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;
关于Perl:如何从严格的 perl 文件使用其他 pl 文件中定义的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63600589/