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

command linegetoptperl

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.

Best Answer

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;