Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获取Perl';s Getopt::Long是否要告诉您是否缺少参数?_Perl_Command Line Arguments - Fatal编程技术网

如何获取Perl';s Getopt::Long是否要告诉您是否缺少参数?

如何获取Perl';s Getopt::Long是否要告诉您是否缺少参数?,perl,command-line-arguments,Perl,Command Line Arguments,我正在使用Perl的模块来解析命令行参数。但是,即使缺少一些参数,它也会返回一个真值。有没有办法判断情况是否如此?选项是可选的,因此名称为“Getopt” 检查由Getopt::Long设置的选项值;如果其中一个关键参数是“undef”,则它已丢失,您可以识别它 返回值告诉您命令行中没有可怕的错误。错误的构成取决于您如何使用Getopt::Long,但经典的错误是命令行包含-o输出,但命令无法识别-o选项。在普通的Getopt::Long中,您不能直接执行此操作——正如Jonathan所说的,您

我正在使用Perl的模块来解析命令行参数。但是,即使缺少一些参数,它也会返回一个真值。有没有办法判断情况是否如此?

选项是可选的,因此名称为“Getopt”

检查由
Getopt::Long
设置的选项值;如果其中一个关键参数是“
undef
”,则它已丢失,您可以识别它


返回值告诉您命令行中没有可怕的错误。错误的构成取决于您如何使用
Getopt::Long
,但经典的错误是命令行包含
-o输出
,但命令无法识别
-o
选项。

在普通的Getopt::Long中,您不能直接执行此操作——正如Jonathan所说的,您需要检查您的未定义需求。然而,这是一件好事——什么是“必需”参数?通常情况下,在一种情况下需要参数,而在另一种情况下不需要参数——这里最常见的例子是
--help
选项。它不是必需的,如果用户使用它,他可能不知道或不会传递任何其他“必需”参数

我在我的一些代码中使用了这个习惯用法(嗯,我以前是这样的,直到我改用):

即使使用MooseX::Getopt,我也不会将属性设置为
required=>1
,同样是因为
--help
选项。相反,在进入程序执行的主体之前,我检查是否存在我需要的所有属性

package MyApp::Prog;
use Moose;
with 'MooseX::Getopt';

has foo => (
    is => 'ro', isa => 'Str',
    documentation => 'Provides the foo for the frobnitz',
);
has bar => (
    is => 'ro', isa => 'Int',
    documentation => 'Quantity of bar furbles to use when creating the frobnitz',
);

# run just after startup; use to verify system, initialize DB etc.
sub setup
{
    my $this = shift;

    die "Required option foo!\n" unless $this->foo;
    die "Required option bar!\n" unless $this->bar;

    # ...
}

有时选项不是可选的。@tster:我同意;有时,命令确实需要一些特定的选项才能显示——如果能够通知Getopt包情况就是这样,那就太好了。也许其他一些Getopt包也支持这一点?有很多选择(我也有自己的选择——但它不支持强制论点)。有一种观点认为强制性期权不应该在前面加一个负号;它们成为位置论点。然而,如果有几个这样的论点,位置很快就会变得难以记忆。这是个好问题。我希望除了检查undef的值之外,还有其他方法可以做到这一点。这是可以理解的,为什么这么多人会感到困惑,因为Getopt的文档暗示您可以指定所需的选项。对于具有值的选项,必须指定是否需要该选项值,以及该选项期望的值类型
package MyApp::Prog;
use Moose;
with 'MooseX::Getopt';

has foo => (
    is => 'ro', isa => 'Str',
    documentation => 'Provides the foo for the frobnitz',
);
has bar => (
    is => 'ro', isa => 'Int',
    documentation => 'Quantity of bar furbles to use when creating the frobnitz',
);

# run just after startup; use to verify system, initialize DB etc.
sub setup
{
    my $this = shift;

    die "Required option foo!\n" unless $this->foo;
    die "Required option bar!\n" unless $this->bar;

    # ...
}