模块文件中的常量是否应该自动导入?
Are constants in module files supposed to be imported automatically?
给定模块文件test.pm6
:
constant $AUTHOR='me';
和脚本 test_script.p6
:
use lib '.';
use test;
my $AUTHOR = 'someone';
我在编译检查时收到以下警告 test_script.p6
:
perl6 -c test_script.p6
Potential difficulties:
Redeclaration of symbol '$AUTHOR'
at test_script.p6:5
------> my $AUTHOR⏏ = 'someone';
Syntax OK
但是,只需将 test.pm6
更改为以下其中一项即可使此警告消失:
my $AUTHOR='me';
或
my constant $AUTHOR='me';
所以,问题是常量是否应该自动导入还是这是一个错误?
这是使用安装在 CentOS Linux 版本 7.3.1611(核心)上的 Rakudo Star 2017.01 Release Candidate 0。
这不是错误。默认情况下,常量在 our
范围内,并且 test.pm6
中的常量仍在主线中,因此被放置在 GLOBAL
命名空间中,因为它是 our
,它在你的主脚本.
避免它的一种方法是您发现的:在 constants/classes 上使用 my
(因为它们默认为 our
)。或者相反,在 subroutines/variables 上使用您想要显示的 our
(因为 subs 默认为 my
)。
另一种方法是在模块文件的顶部使用 unit module BlahBlah;
,然后这些符号将位于 BlahBlah
命名空间中,而不是 GLOBAL
中,依此类推将不会直接在主脚本中可见(our
符号仍然可以作为 BlahBlah::whatever
访问)
P.S.: 那些在 2016 Rakudos 上的人不会观察到这种行为,因为 lexical module loading bug,它只在 2017.01 编译器版本中得到修复(并在 2016.12 之后的几天被合并到 master编译器版本)
给定模块文件test.pm6
:
constant $AUTHOR='me';
和脚本 test_script.p6
:
use lib '.';
use test;
my $AUTHOR = 'someone';
我在编译检查时收到以下警告 test_script.p6
:
perl6 -c test_script.p6
Potential difficulties:
Redeclaration of symbol '$AUTHOR'
at test_script.p6:5
------> my $AUTHOR⏏ = 'someone';
Syntax OK
但是,只需将 test.pm6
更改为以下其中一项即可使此警告消失:
my $AUTHOR='me';
或
my constant $AUTHOR='me';
所以,问题是常量是否应该自动导入还是这是一个错误?
这是使用安装在 CentOS Linux 版本 7.3.1611(核心)上的 Rakudo Star 2017.01 Release Candidate 0。
这不是错误。默认情况下,常量在 our
范围内,并且 test.pm6
中的常量仍在主线中,因此被放置在 GLOBAL
命名空间中,因为它是 our
,它在你的主脚本.
避免它的一种方法是您发现的:在 constants/classes 上使用 my
(因为它们默认为 our
)。或者相反,在 subroutines/variables 上使用您想要显示的 our
(因为 subs 默认为 my
)。
另一种方法是在模块文件的顶部使用 unit module BlahBlah;
,然后这些符号将位于 BlahBlah
命名空间中,而不是 GLOBAL
中,依此类推将不会直接在主脚本中可见(our
符号仍然可以作为 BlahBlah::whatever
访问)
P.S.: 那些在 2016 Rakudos 上的人不会观察到这种行为,因为 lexical module loading bug,它只在 2017.01 编译器版本中得到修复(并在 2016.12 之后的几天被合并到 master编译器版本)