Processing Command Line Options with PERL - Negative Reinforcement (
Page 8 of 9 )
An interesting feature in Getopt::Long.pm is its ability to also support option negation - that is, disable an option by prefixing it with "no". For example, this means that while you could explicitly activate the "trace" option by sending the program "--trace" on the command line, you could also explicitly disable it by sending "--no-trace". However, it's only possible to do this with Boolean options, which can be set to either true or false; you can't do it with options that require numeric or string values.
In order to do this, simply add an exclamation (!) as negation symbol after the option name in the call to GetOptions() - as in the following example:
#!/usr/bin/perl
# import module
use Getopt::Long;
# read options
$result = GetOptions ( "eyes!" => $sight,
"nose!" => $smell,
"ears!" => $hearing );
# print values
$sight ? print "Can see!n" : print "Cannot see!n";
$smell ? print "Can smell!n" : print "Cannot smell!n"; $hearing ?
print "Can hear!n" : print "Cannot hear!n";
A user could now do something like this:
$ ./script.pl --no-eyes --no-ears --no-nose
Cannot see!
Cannot smell!
Cannot hear!
Note that there's an important difference between explicitly disabling an option in this manner, and not passing the option to the program at all. In the former case, Getopt::Long.pm sets the corresponding option variable to false or 0; in the latter, the option variable is null (or whatever default value it was assigned initially). Consider the following example, which illustrates this difference:
#!/usr/bin/perl
# import module
use Getopt::Long;
# default value for counter
$counter = -1;
# read options
$result = GetOptions ("counter!" => $counter);
# print values
print "Counter is $counter";
Here's the output:
$ ./script.pl --counter
Counter is 1
$ ./script.pl --no-counter
Counter is 0
$ ./script.pl
Counter is -1