问题
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