问题描述
我有一个脚本,它可以使用 Getopt::Long
获取数十个参数/标志.某些标志不允许混合使用,例如:--linux --unix
不允许一起提供.我知道我可以使用 if
语句进行检查.有没有更干净、更好的方法来做到这一点?
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
块会变得丑陋.
推荐答案
Getopt 似乎没有::Long 有这样的功能,快速搜索 CPAN.但是,如果您可以使用散列来存储您的选项,那么创建您自己的函数似乎不会太难看:
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;
}
}
这也适用于 2 个以上的选项:
This also scales to more than 2 options:
mutex(qw(linux unix windoze));
这篇关于避免将某些参数混合到脚本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!