【问题标题】:Having trouble with the one_of feature in Getopt::Long::DescriptiveGetopt::Long::Descriptive 中的 one_of 功能有问题
【发布时间】:2019-08-13 15:31:51
【问题描述】:

当我在 Getopt::Long::Descriptive 中使用“one_of”特殊规范时,我在命令行中not 放置的选项会出错。我想让 Getopt::Long::Descriptive 为我处理互斥选项;但我不知道如何使用规范而不产生错误。

如果我在 one_of 说明符中列出 没有 的选项,它们会按预期工作。但是,我可以在命令行上放置多个应该互斥的选项。 Perl 5.26.1 和 Getopt::Long::Descriptive 0.104 如果有帮助的话。

use Getopt::Long::Descriptive;

my $usage_desc = "%c %o mailbox|ticket <This script lists or adds stuff>";
my @opt_spec   = (
    [
        "mode" => hidden => {
            one_of => [
                [ 'list|l=s' => 'lists stuff' ],
                [ 'add|a=s' => 'adds stuff' ],
            ]
        }
    ],
    [ 'verbose|v' => 'increase the verbosity level in the log file' ],
    [ 'help'      => 'print usage message and exit', { shortcircuit => 1 } ],
);

my ( $opt, $usage ) = describe_options( $usage_desc, @opt_spec );

print( $usage->text ), exit if $opt->help;

if ( $opt->verbose ) {
    $debug_level++;
    print "option --verbose specified; debug level now at $debug_level\n";
}

if ( $opt->list ) {
    my $argument = $opt->list;
    print "option --list specified, with argument: $argument\n";
}

if ( $opt->add ) {
    my $argument = $opt->add;
    print "option --add specified, with argument: $argument\n";
}

foreach my $argument ( @ARGV ) {
    print "argument '$argument\' supplied (without an option specified)\n";
    handle_search_terms( $argument );
}

当我运行我的脚本时,例如使用 --list foo,然后我得到一个错误

"Can't locate object method "add" via package "Getopt::Long::Descriptive::Opts::__OPT__::1" at line 38."

如果我使用 --add bar 运行它,则会收到错误“无法通过包定位对象方法“列表”......”

我的问题是我不知道如何构造我的代码,以便使用 not 的选项不会产生错误。

【问题讨论】:

标签: perl


【解决方案1】:
if ( $opt->mode eq 'list' ) {
    my $argument = $opt->list;
    print "option --list specified, with argument: $argument\n";
}
elsif ( $opt->mode eq 'add' ) {
    my $argument = $opt->add;
    print "option --add specified, with argument: $argument\n";
}

别忘了:

use strict;
use warnings;

所有这些都是described in the documentation

【讨论】:

  • 非常感谢!我对 Perl 有点陌生,并且认为我以前从未使用过 elsif 构造。对于它的价值,我需要添加 if(defined $opt->mode ){} 作为整个 iff .. elseif 片段的包装,以让脚本处理提供没有选项的参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多