Avoiding mix of certain arguments to script

早过忘川 提交于 2019-12-06 02:57:40

问题


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. Now I know I can check using an if statement, but I'm sure 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.

Any suggestions?

Thanks,


回答1:


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


来源:https://stackoverflow.com/questions/10299007/avoiding-mix-of-certain-arguments-to-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!