如何将强制和可选命令行参数传递给 perl 脚本?

2024-03-15

我正在使用 Getopt::Long 将选项传递给我的 Perl 脚本。

但我想做这样的事情:

perl myScript mandatoryArgument1 -optionalArgument1=someValue

我希望脚本在缺少 CommandArgument1 时抛出错误。如何才能做到这一点?


好的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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将强制和可选命令行参数传递给 perl 脚本? 的相关文章

随机推荐