好的Getopt::Long
没有这方面的机制。它具体流程options http://perldoc.perl.org/Getopt/Long.html#GetOptions-does-not-return-a-false-result-when-an-option-is-not-supplied.
然而,当它完成工作时,它会从@ARGV
因此,一旦完成,您就可以检查是否存在预期的参数。请参阅第二部分,但我想首先建议另一种方法:使这些参数命名,然后Getopt
将处理它们。
然后很容易检查它们是否已提交。例如
use warnings;
use strict;
use feature 'say';
use Getopt::Long;
my $mandatoryArg;
my $opt;
# Read command-line arguments, exit with usage message in case of error
GetOptions( 'name=s' => \$mandatoryArg, 'flag' => \$opt )
or usage();
if (not defined $mandatoryArg) {
say STDERR "Argument 'name' is mandatory";
usage();
}
# The program goes now. Value for $opt may or may have not been supplied
sub usage {
say STDERR "Usage: $0 ..."; # full usage message
exit;
}
So if --name string
命令行上没有给出$mandatoryArg
保持未定义状态并且程序退出。该变量不需要默认值,因为它是强制性的,并且不应该有一个默认值才能使此检查起作用。
参数检查和处理通常要复杂得多,此时Getopt
shines.
The mandatoryArgument1
in the question is supplied without a name. While Getopt
can be made to act on a non-option input http://perldoc.perl.org/Getopt/Long.html#Argument-callback, it cannot detect that an expected one is not there.†
该模块确实允许在命令行的任何位置将参数与命名选项混合。看带有其他参数的选项 http://perldoc.perl.org/Getopt/Long.html#Mixing-command-line-option-with-other-arguments在文档中。所以你可以调用该程序
script.pl --opt1 value1 unnamed_arg --opt2 value2
但我建议用户在命名选项后提供它们。
然后GetOptions
尽其职责,@ARGV
将包含字符串unnamed_arg
你可以得到它(或者发现它不在那里)。命名选项的处理GetOptions
与上面相同。
my ($var1, $var2, $flag);
GetOptions('opt1=s' => \$var1, 'opt2=i' => \$var2, 'f' => \$flag)
or usage();
# All supplied named options have been collected, all else left in @ARGV
# Read the remaining argument(s) from @ARGV, or exit with message
# This can get far more complicated if more than one is expected
my $mandatoryArg1 = shift @ARGV || do {
say STDERR "Mandatory argument (description) is missing";
usage();
};
以上你必须处理@ARGV
用手一次Getopt
选取了命名参数。
如果存在多个这样的参数,则用户必须严格遵守其在命令行上的预期相对位置,因为程序通常无法分辨什么是什么。因此,用户在命令行上混淆命令的错误通常无法被捕获。
这成为一个障碍,我建议最多一个一种未命名的参数,并且只有在很明显它必须是什么的情况下,例如文件名。
虽然所有这些都是可能的模块,例如Getopt
正是存在,所以我们不必这样做。
† Action for input that doesn't look like an option is set up using the "name" of '<>'
Getoptions( 'opt=s' => \$var, ..., '<>' => \&arg_cb );
sub arg_cb { say "Doesn't look like an option: $_[0]" }
其中子arg_cb
仅当非选项参数时才被调用is seen.