Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Getopt::Long Related Question - Mutually Exclusive Command-Line Arguments

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.

like image 690
Dr. Faust Avatar asked May 20 '09 16:05

Dr. Faust


2 Answers

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):

die usage() if defined $directory and @files;
like image 72
Chas. Owens Avatar answered Nov 15 '22 09:11

Chas. Owens


Why not just this:

if ($directory && @files) {
  die "dir and files options are mutually exclusive\n";
}
like image 29
Alex Avatar answered Nov 15 '22 10:11

Alex