我想在我的Perl程序中启用/禁用使用Smart :: Comments模块的注释。我通过提供--verbose开关作为命令行选项列表的一部分,玩弄了这样做的想法。设置此开关后,我正在考虑启用Smart :: Comment模块,如下所示:
#!/usr/bin/perl
use Getopt::Long;
use Smart::Comments;
my $verbose = 0;
GetOptions ('verbose' => \$verbose);
if (! $verbose) {
eval "no Smart::Comments";
}
### verbose state: $verbose
然而,这对我不起作用。它似乎与Smart :: Comments本身的工作方式有关,所以我怀疑我试图用eval“no ...”位来禁用模块的方式。任何人都可以就此提供一些指导吗?
答案 0 :(得分:10)
从脚本中取出use Smart::Comments
行,并使用或不使用-MSmart::Comments
选项运行脚本。使用-M<module>
选项就像在脚本的开头添加use <module>
语句。
# Smart comments off
$ perl my_script.pl
# Smart comments on
$ perl -MSmart::Comments my_script.pl ...
另请参阅Smart::Comments
文档中的$ENV{Smart_Comments}
变量。
在这里,您可以在脚本中使用Smart::Comments
,如
use Smart::Comments -ENV;
然后运行
$ perl my_script.pl
$ Smart_Comments=0 perl my_script.pl
在没有智能评论的情况下运行,
$ Smart_Comments=1 perl my_script.pl
运行智能评论。
更新 Smart::Comments
模块是源过滤器。试图在运行时打开和关闭它(例如,eval "no Smart::Comments"
)将不起作用。充其量,您可以在编译时进行一些配置(例如,在BEGIN{}
块中,在加载Smart::Comments
之前):
use strict;
use warnings;
BEGIN { $ENV{Smart_Comments} = " @ARGV " =~ / --verbose / }
use Smart::Comments -ENV;
...
答案 1 :(得分:0)
使用“if”pragma:
use if !$ENV{MY_APP_NDEBUG}, 'Smart::Comments';
# or
use if $ENV{MY_APP_DEBUG}, 'Smart::Comments';
如果不需要,则不会加载Smart :: Comments。