使用if pragma有条件地包括Perl模块时出错 [英] Error in conditionally including Perl module using if pragma
问题描述
这很好:
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.
这篇关于使用if pragma有条件地包括Perl模块时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!