有没有办法通过我的Perl程序中的命令行开关启用/禁用Smart :: Comments?

slm*_*slm 4 perl perl-module

我想在我的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
Run Code Online (Sandbox Code Playgroud)

然而,这对我不起作用.它似乎与Smart :: Comments本身的工作方式有关,所以我怀疑我试图用eval"no ..."位来禁用模块的方式.有人可以给我一些指导吗?

mob*_*mob 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 ...
Run Code Online (Sandbox Code Playgroud)

另请参阅文档中的$ENV{Smart_Comments}变量Smart::Comments.在这里,您将Smart::Comments在您的脚本中使用

use Smart::Comments -ENV;
Run Code Online (Sandbox Code Playgroud)

然后跑

$ perl my_script.pl 
$ Smart_Comments=0 perl my_script.pl
Run Code Online (Sandbox Code Playgroud)

没有聪明的评论,并且

$ Smart_Comments=1 perl my_script.pl
Run Code Online (Sandbox Code Playgroud)

运行聪明的评论.


更新Smart::Comments模块是一个源滤波器.试图在运行时(例如eval "no Smart::Comments")打开和关闭它将无法正常工作.充其量,您可以在编译时进行一些配置(例如,在BEGIN{}加载前的块中Smart::Comments):

use strict;
use warnings;
BEGIN { $ENV{Smart_Comments} = " @ARGV " =~ / --verbose / }
use Smart::Comments -ENV;
...
Run Code Online (Sandbox Code Playgroud)