【问题标题】:Checking multiple mutually exclusive options in perl's getopt检查 perl 的 getopt 中的多个互斥选项
【发布时间】:2012-06-11 03:13:11
【问题描述】:

如何检查是否只定义了 -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;
}

以上方法可行,但不是很优雅

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

【问题讨论】:

    标签: perl


    【解决方案1】:

    或者你可以:

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

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

    【讨论】:

    • > 无论如何都会强制执行标量上下文,并且不需要defined 检查,所以这可能是die "error" if grep($_, $opt_a, $opt_b, $opt_c) > 1
    【解决方案2】:
    sub is_here_multiple { ( sum map $_?1:0, @_ ) > 1 }
    

    sumList::Util 提供。


    哦,对了,grep 在标量上下文中很重要,所以您只需要

    sub is_here_multiple { ( grep $_, @_ ) > 1 }
    

    【讨论】:

    • 它在“sum map”附近的 xx 行 9 处抛出“语法错误”。“sum” - 来自哪里?perldoc -f sum 不知道。
    • 装鲤鱼的人说。你认为哪一个是“大模块”。无论如何,请随意写自己的sum
    猜你喜欢
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 2018-02-04
    • 2014-06-19
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多