且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用"use strict"导入常量,避免“不能使用beadword ...作为ARRAY ref";

更新时间: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.

该方法包括以下内容:

  1. 在脚本开头的BEGIN块中按原样放置整个模块.
  2. 将尾随的1;替换为$INC{"Foo/Bar.pm"} = 1;(用于Foo::Bar).
  1. Place the entire module as-is in a BEGIN block at the start of the script.
  2. Replace the trailing 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,

  • 如果您需要5.18,则***启用它提供的语言功能.这是通过将required 5.018;替换为use 5.018;来完成的
    • 我们不需要显式使用use strict;,因为use 5.012;及更高版本可以实现严格要求.
    • 我们可以使用say,因为use 5.010;启用了它.
    • If you're going to requires 5.18, might as well enable the language features it provides. This was done by replacing required 5.018; with use 5.018;
      • We don't need to use use strict; explicitly because use 5.012; and higher enable strictures.
      • We can use say because use 5.010; enables it.