使用if pragma有条件地包括Perl模块时出错

问题描述:

这很好:

use if (1), 'x86_64-linux-thread-multi::Devel::Cover::DB::IO::JSON';

但不是这样:

my $a=1;
use if ($a), 'x86_64-linux-thread-multi::Devel::Cover::DB::IO::JSON';

稍后打印错误Can't locate object method "new" via package "JSON" (perhaps you forgot to load "JSON"?) at ./script.pl line 100.,我在第100行中有$json = JSON->new;.

later prints error Can't locate object method "new" via package "JSON" (perhaps you forgot to load "JSON"?) at ./script.pl line 100., I have $json = JSON->new; in line 100.

我正在使用Perl 5.16.2版本,有什么帮助吗?预先感谢.

I am using Perl 5.16.2 version, any help? thanks in advance.

对变量的分配在运行时发生,而use在编译时进行.因此,在您的示例中,use发生时尚未为$a分配任何值,因此其值为undef.

Assignment to variables happens at run time, while use happens at compile time. So in your example, $a has not been assigned any value when the use happens, so it evaluates to undef.

要在编译时分配给$a,请使用BEGIN:

To assign to $a at compile time, use BEGIN:

my $a;
BEGIN { $a = 1 }
use if ($a), 'x86_64-linux-thread-multi::Devel::Cover::DB::IO::JSON';

您还应该知道,使变量$a$b成为词法通常是令人讨厌的,因为这会干扰sort函数的正常操作.

You should also be aware that making the variables $a and $b lexical is generally frowned upon, since it interferes with the normal operation of the sort function.