【问题标题】:How can I configure the perl App::Cmd module to complain about incorrect options如何配置 perl App::Cmd 模块以抱怨不正确的选项
【发布时间】:2013-06-14 15:53:10
【问题描述】:

我正在尝试使用 perl App::Cmd 模块,一个简单的测试程序可以正常工作。

但是,如果我使用未在 opt_spec 中配置的 --option 运行程序 函数(我正在调用的子命令),它不会抱怨无效的选项。我希望它会这样做。相反,它只是默默地忽略了该选项。

无论如何我都看不到配置 App::Cmd 来抱怨无效选项。

这可能吗,还是每个子命令都应该自己进行检查?

谢谢

【问题讨论】:

    标签: perl cpan


    【解决方案1】:

    根据 App::Cmd 教程 https://metacpan.org/dist/App-Cmd/view/lib/App/Cmd/Tutorial.pod 参数由 Getopt::Long::Descriptive (GLD) 处理(检查参数和选项部分 https://metacpan.org/dist/App-Cmd/view/lib/App/Cmd/Tutorial.pod#Arguments-and-Options

    例如jobstatus是一个命令,需要job id作为参数

    mycli jobstatus -j 1111 or mycli jobstatus --jobid 1111 #有效的命令选项

    sub opt_spec {
      # check https://metacpan.org/pod/Getopt::Long#Summary-of-Option-Specifications
      return (
        [ "jobid|j=i",  "specify job id" ],
      );
    }
    
    sub validate_args {
      my ($self, $opt, $args) = @_;
      # The $opt object will be a dynamically-generated subclass of Getopt::Long::Descriptive::Opts. In brief, each of the options in @opt_spec becomes an accessor method on the object, using the first-given name, with dashes converted to underscores.
      # So object $opt->jobid parameter value is 1111 (jobid 1111 consider as option) and -k consider as argument
      $self->usage_error("Please verify given arguments @$args \n") if @$args;
    }
    

    输出

    > perl mycli jobstatus -j 1111 -k
    > Error: Please verify given arguments -k
    
    Usage: mycli <command> [-?h] [long options...]
            -? -h --help  show help
    
    mycli jobstatus [-j] [long options...]
            -j INT --jobid INT  specify job id
    

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 2017-12-26
      • 2017-01-18
      • 2021-12-13
      • 2016-11-03
      相关资源
      最近更新 更多