使用if pragma有条件地包括Perl模块时出错 [英] Error in conditionally including Perl module using if pragma

查看:121
本文介绍了使用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.

这篇关于使用if pragma有条件地包括Perl模块时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆