Avoiding mix of certain arguments to script

后端 未结 1 646
走了就别回头了
走了就别回头了 2021-01-05 08:15

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 no

相关标签:
1条回答
  • 2021-01-05 09:02

    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));
    
    0 讨论(0)
提交回复
热议问题