Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to enable/disable Smart::Comments via a command line switch in my Perl program?

I'd like to enable/disable the comments within my Perl program that make use of the module Smart::Comments. I've toyed with the idea of doing this by providing a --verbose switch as part of my list of command line options. When this switch is set, I was thinking of enabling the Smart::Comment module like so:

#!/usr/bin/perl

use Getopt::Long;
use Smart::Comments;

my $verbose = 0;
GetOptions ('verbose' => \$verbose);

if (! $verbose) {
  eval "no Smart::Comments";
}
### verbose state: $verbose

However this doesn't work for me. It seems to be something with the way Smart::Comments itself works, so I'm suspicious of the way in which I'm trying to disable the module with the eval "no ..." bit. Can anyone offer me some guidance on this?

like image 902
slm Avatar asked Dec 28 '22 11:12

slm


1 Answers

Take out the use Smart::Comments line out of the script, and run you script with or without the -MSmart::Comments option. Using the -M<module> option is like putting a use <module> statement at the beginning of your script.

# Smart comments off
$ perl my_script.pl

# Smart comments on
$ perl -MSmart::Comments my_script.pl ...

Also see the $ENV{Smart_Comments} variable in the Smart::Comments docs. Here, you would use Smart::Comments in your script like

use Smart::Comments -ENV;

and then run

$ perl my_script.pl 
$ Smart_Comments=0 perl my_script.pl

to run without smart comments, and

$ Smart_Comments=1 perl my_script.pl

to run with smart comments.


Update The Smart::Comments module is a source filter. Trying to turn it on and off at runtime (e.g., eval "no Smart::Comments") won't work. At best, you can do some configuration at compile time (say, in a BEGIN{} block, before loading Smart::Comments):

use strict;
use warnings;
BEGIN { $ENV{Smart_Comments} = " @ARGV " =~ / --verbose / }
use Smart::Comments -ENV;
...
like image 81
mob Avatar answered Jan 29 '23 14:01

mob