So my goal is to find an easy way to turn on print statements in Perl using a flag. In C/C++ you can use a #define to choose if certain code is run and it is a way to turn on and off debug print statements. If a #define DEBUG is defined, then you print something, else you run it without the print statements. I was wondering if there was an easy way to do this in Perl.
Here is an example of how it would work:
for($i = 0 ; $i < 10; $i++){
if(debug flag){
print some info;
}
do operational stuff.
}
Now from the command line you could do one of two things:
1.Run without the debug print statements
perlScript.pl
2.Run with debug print statements
perlScript.pl -debug
Or if someone has a better idea please let me know!
In perl, compile time is also run time. So there's really not a great deal of advantage in using #define
type statements.
My usual trick is:
my $debug = 0;
$debug += scalar grep ( "-d", @ARGV );
(GetOpt
is probably honestly a better plan though)
And then use:
print if $debug;
print $statement if $debug > 2;
Which means I've an easy way of setting the verbosity, and also allowing me to be selective about it by incrementing the statements.
Sometimes I'll embed a signal handler to also adjust debugging level -
#!/usr/bin/perl
use strict;
use warnings;
my $debug = 0;
$debug += scalar grep ( "-d", @ARGV );
$SIG{'USR1'} = { $debug++ };
$SIG{'USR2'} = { $debug-- };
while ( 1 ) {
print "Debugging at: $debug\n";
sleep 1;
}
It's more a question of what sort of code I'm writing - this latter I particularly like when doing fork
y stuff, because then I can adjust debug levels in each fork independently and on the fly.