Dav*_*d B 9 perl command-line-arguments
我正在使用Perl的Getopt :: Long模块来解析命令行参数.但是,即使缺少某些参数,它似乎也会返回一个真值.有没有办法判断是否是这种情况?
选项是可选的,因此名称为“Getopt”。
您检查由设置的选项值Getopt::Long;如果其中一个关键是“ undef”,则它被遗漏了,您可以识别它。
返回值告诉您命令行中没有可怕的错误。什么构成错误取决于您如何使用Getopt::Long,但经典的错误是命令行包含-o output但命令不识别-o选项。
在普通的旧Getopt :: Long中,你不能直接这样做 - 正如Jonathan所说,你需要检查你对undef的要求.但是,恕我直言,这是一件好事 - 什么是"必需"参数?通常一个参数在一个案例中而不是另一个案例中是必需的 - 这里最常见的例子是--help选项的疼痛拇指.这不是必需的,如果用户使用它,他可能不知道或不会传递任何其他"必需"参数.
我在我的一些代码中使用这个成语(好吧,我曾经,直到我切换到使用MooseX :: Getopt):
use List:MoreUtils 'all';
Getopt::Long::GetOptions(\%options, @opt_spec);
print usage(), exit if $options{help};
die usage() unless all { defined $options{$_} } @required_options;
Run Code Online (Sandbox Code Playgroud)
即使使用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;
# ...
}
Run Code Online (Sandbox Code Playgroud)