如果在 Perl 中找不到所需的参数,则退出脚本
Exit from the script if required arguments not found in Perl
我有一个脚本,它应该从命令行获取两个参数。为此,我使用了 Getopt::Long
Perl 模块。
这是脚本:
#!/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:$node\nCmd:$command\n";
doSomeOpearation($node, $command);
print "END\n";
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
消息。
除非有 2 个参数,否则如何打印 HelpMessage
并退出脚本?
您的支票来得太晚了。
doSomeOpearation($node, $command);
...
HelpMessage(1) unless ($node && $command);
应该是
HelpMessage(1) unless ($node && $command);
doSomeOpearation($node, $command);
...
我有一个脚本,它应该从命令行获取两个参数。为此,我使用了 Getopt::Long
Perl 模块。
这是脚本:
#!/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:$node\nCmd:$command\n";
doSomeOpearation($node, $command);
print "END\n";
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
消息。
除非有 2 个参数,否则如何打印 HelpMessage
并退出脚本?
您的支票来得太晚了。
doSomeOpearation($node, $command);
...
HelpMessage(1) unless ($node && $command);
应该是
HelpMessage(1) unless ($node && $command);
doSomeOpearation($node, $command);
...