如果在Perl中找不到所需的参数,请退出脚本



我有一个脚本,它应该从命令行中获取两个参数。为了实现这一点,我使用了Getopt::LongPerl模块。

这是脚本:

#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long 'HelpMessage';
GetOptions(
'node|n=s' => my $node,
'cmd|c=s'  => my $command,
'help'     =>  sub { HelpMessage(0) }
) or HelpMessage(1);
print "Node:$nodenCmd:$commandn";
doSomeOpearation($node, $command);
print "ENDn";
sub doSomeOpearation {
my ($n, $c) = @_;
#...
return;
}
HelpMessage(1) unless ($node && $command);
=head1 NAME
run_command - Run Commands on SVC Server
=head1 SYNOPSIS
--node,-n       Node name (required)
--command,-c    Command (required)
--help,-h       Print this help
=head1 VERSION
1.00
=cut

脚本在积极的场景中运行良好,即,如果我向脚本传递2个参数,它将在屏幕中打印这些参数。

但是,如果我只给脚本传递一个参数,它应该转到HelpMessage函数。相反,这里的脚本会给我Use of uninitialized value $command in concatenation (.) or string at script2.pl line 14.警告,并打印END消息。

除非有两个参数,否则我如何打印HelpMessage并退出脚本?

您的支票来得太晚了。

doSomeOpearation($node, $command);
...
HelpMessage(1) unless ($node && $command);

应该是

HelpMessage(1) unless ($node && $command);
doSomeOpearation($node, $command);
...

最新更新