5

如何检查是否只定义了-aor -bor之一-c

所以不在一起-a -b,也不-a -c,也不-b -c,也不-a -b -c

现在有

use strict;
use warnings;
use Carp;
use Getopt::Std;

our($opt_a, $opt_b, $opt_c);
getopts("abc");

croak("Options -a -b -c are mutually exclusive")
        if ( is_here_multiple($opt_a, $opt_c, $opt_c) );

sub is_here_multiple {
        my $x = 0;
        foreach my $arg (@_) { $x++ if (defined($arg) || $arg); }
        return $x > 1 ? 1 : 0;
}

以上工作,但不是很优雅

这里已经是类似的问题,但这是不同的,因为检查两个独占值很容易 - 但这里有多个。

4

2 回答 2

3

或者您可以:

die "error" if ( scalar grep { defined($_) || $_  } $opt_a, $opt_b, $opt_c  ) > 1;

标量上下文中的 grep 返回匹配元素的计数。

于 2012-06-10T07:48:43.660 回答
1
sub is_here_multiple { ( sum map $_?1:0, @_ ) > 1 }

sumList::Util提供。


哦,对了,grep在标量上下文中计数,所以你只需要

sub is_here_multiple { ( grep $_, @_ ) > 1 }
于 2012-06-10T07:27:38.170 回答