I have the following code in my perl script:
my $directory; my @files; my $help; my $man; my $verbose; undef $directory; undef @files; undef $help; undef $man; undef $verbose; GetOptions( "dir=s" => \$directory, # optional variable with default value (false) "files=s" => \@files, # optional variable that allows comma-separated # list of file names as well as multiple # occurrenceces of this option. "help|?" => \$help, # optional variable with default value (false) "man" => \$man, # optional variable with default value (false) "verbose" => \$verbose # optional variable with default value (false) ); if (@files) { @files = split(/,/,join(',', @files)); }
What is the best way to handle mutually exclusive command line arguments? In my script I only want the user to enter only the "--dir" or "--files" command line argument but not both. Is there anyway to configure Getopt to do this?
Thanks.
You can do this with
Getopt::Long::Descriptive
. It's a bit different fromGetopt::Long
, but if you're printing a usage summary, it helps to reduce duplication by doing all that for you.Here, I've added a hidden option called
source
, so$opt->source
which will contain the valuedir
orfiles
depending on which option was given, and it will enforce theone_of
constraint for you. The values given will be in$opt->dir
or$opt->files
, whichever one was given.The main difference for the rest of your script is that all the options are contained as methods of the
$opt
variable, rather than each one having its own variable like withGetopt::Long
.I don't think there is a way in Getopt::Long to do that, but it is easy enough to implement on your own (I am assuming there is a usage function that returns a string that tells the user how to call the program):
You can simply check for the existence of values in both variables.
Or, if you would like to simply ignore any options specified after the first --dir or --files, you can point both at a function.
Why not just this: