我是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: $0 --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
}
答案 0 :(得分:1)
调用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: $0 --from NAME --to NAME\n";
@ARGV and die "Error: unexpected args: @ARGV";
if ($source_address) {
say $source_address;
}
if ($dest_address) {
say $dest_address;
}
答案 1 :(得分:1)
我忙着回答,我看到现在已经回答,只是一些额外的信息。
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: $0 --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.
}
所以简而言之