在 perl 的 getopt 中检查多个互斥选项

caj*_*ine 5 perl

如何检查不仅仅是一个-a-b-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;
}
Run Code Online (Sandbox Code Playgroud)

以上是有效的,但不是很优雅

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

jm6*_*666 3

或者您可以:

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

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