如何使用 GetOptions 检测尾随字符串?

How to use GetOptions to detect trailing strings?

我对 Perl 完全陌生,我正在尝试找出 Perl 脚本解析脚本参数的问题。

我有以下名为 sample-perl.pl 的 Perl 脚本:

use strict;
use warnings;
use 5.010;
use Getopt::Long qw(GetOptions);

my $source_address;
my $dest_address;

GetOptions('from=s' => $source_address,
           'to=s' => $dest_address) or die "Usage: [=10=] --from NAME --to NAME\n";
if ($source_address) {
    say $source_address;
}

if ($dest_address) {
    say $dest_address;
}

如果我使用像这样的命令(我忘记输入第二个选项):

perl sample-perl.pl --from nyc lon
Output will be: nyc

如果末尾有一个额外的字符串,我该如何强制检测到它并显示错误?

解决方案:

添加这个至少对我的情况有帮助:

if(@ARGV){
    //throw error
}

调用 GetOptions 后,检查 @ARGV 数组中是否有任何剩余的命令行选项。这假设所有意外参数都会产生错误:

use strict;
use warnings;
use 5.010;
use Getopt::Long qw(GetOptions);

my $source_address;
my $dest_address;

GetOptions('from=s' => $source_address,
           'to=s' => $dest_address) or die "Usage: [=10=] --from NAME --to NAME\n";

@ARGV and die "Error: unexpected args: @ARGV";

if ($source_address) {
    say $source_address;
}

if ($dest_address) {
    say $dest_address;
}

我正忙着回答,现在看到有人回答了,只是一些额外的信息。

use strict;
use warnings;
use 5.010;
use Getopt::Long qw(GetOptions);

my $source_address;
my $dest_address;

GetOptions('from=s' => $source_address,
       'to=s' => $dest_address) or die "Usage: [=10=] --from NAME --to NAME\n";

@ARGV and die "To many arguments after --from or --to : @ARGV ";

if ($source_address) {
say $source_address;
} else {
say "Error: No Source specified"; #Check to see if --from is actually specified, else print error.
}

if ($dest_address) {
say $dest_address;
} else {
say "Error: No destination specified"; #Check to see if --to is actually specified, else print error.
}

简而言之