更新时间:2023-12-05 23:38:10
在编译对常量的引用之前,需要执行import
.
You need to execute the import
before a reference to the constant is compiled.
您可以使用另一个BEGIN
块来执行此操作,但这意味着我们现在有两个技巧.我建议不要采用以下方法,而不是弗兰肯斯坦对模块的用户和模块本身的看法.它使内联的程序包看起来尽可能多地成为一个真实的模块.
You could use yet another BEGIN
block to do that, but that means we have now two hacks. Rather than frankensteining both the module's user and the module itself, I suggest the following approach. It keeps the inlined package looking as much as a real module as possible.
该方法包括以下内容:
BEGIN
块中按原样放置整个模块.1;
替换为$INC{"Foo/Bar.pm"} = 1;
(用于Foo::Bar
).BEGIN
block at the start of the script.1;
with $INC{"Foo/Bar.pm"} = 1;
(for Foo::Bar
).就是这样.这使您可以像往常一样use
模块.
That's it. This allows you to use
the module as normal.
因此,如果您的模块如下:
So if your module is the following:
package Test;
use strict;
use warnings;
use Exporter qw( import );
our $VERSION = 1.00;
our @EXPORT_OK = qw(AR);
use constant AR => [1,2,3];
1;
如果您的脚本如下:
#!/usr/bin/perl
use 5.018;
use warnings;
use Test qw( AR );
say AR->[1];
您可以使用以下内容:
#!/usr/bin/perl
BEGIN {
package Test;
use strict;
use warnings;
use Exporter qw( import );
our $VERSION = 1.00;
our @EXPORT_OK = qw(AR);
use constant AR => [1,2,3];
$INC{__PACKAGE__ .'.pm'} = 1; # Tell Perl the module is already loaded.
}
use 5.018;
use warnings;
use Test qw( AR );
say AR->[1];
如您所见,我进行了一些清理.具体来说,
As you can see, I've made some cleanups. Specifically,
required 5.018;
替换为use 5.018;
来完成的
use strict;
,因为use 5.012;
及更高版本可以实现严格要求.say
,因为use 5.010;
启用了它.required 5.018;
with use 5.018;
use strict;
explicitly because use 5.012;
and higher enable strictures.say
because use 5.010;
enables it.