7

I have a script which can get tens of arguments/flags using Getopt::Long. Certain flags are not allowed to be mixed, such as: --linux --unix are not allowed to be supplied together. I know I can check using an if statement. Is there is a cleaner and nicer way to do that?

if blocks can get ugly if I don't want to allow many combinations of flags.

toolic
  • 57,801
  • 17
  • 75
  • 117
snoofkin
  • 8,725
  • 14
  • 49
  • 86

1 Answers1

4

It does not seem that Getopt::Long has such a feature, and nothing sticks out after a quick search of CPAN. However, if you can use a hash to store your options, creating your own function doesn't seem too ugly:

use warnings;
use strict;
use Getopt::Long;

my %opts;
GetOptions(\%opts, qw(
    linux
    unix
    help
)) or die;

mutex(qw(linux unix));

sub mutex {
    my @args = @_;
    my $cnt = 0;
    for (@args) {
        $cnt++ if exists $opts{$_};
        die "Error: these options are mutually exclusive: @args" if $cnt > 1;
    }
}

This also scales to more than 2 options:

mutex(qw(linux unix windoze));
toolic
  • 57,801
  • 17
  • 75
  • 117