} = 0; $ OPTIONS {nicName} = $ EMPTY; $ OPTIONS {console} = 0; $ OPTIONS {virtual} = 0; $选项{ CMDB </跨度> } = 0; $ OPTIONS {policyid} = 0锟! =&GT; \ $ OPTIONS {virtual}, ‘NIC | N!’ =&GT; \ $ OPTIONS {nic}, ‘nic-name | m = s’=&gt; \ $ OPTIONS {nicName}, “ CMDB </跨度> | d锟
你不应该在这里使用elsif,因为多个条件可能是真的。由于可能存在多个条件,因此无法使用调度表。您的代码仍然可以大大简化。
my @errors; push @errors, "ERROR: Host must be provided\n" if !defined($OPTIONS{host}); my @conflicting = map { my ($opt, $flag) = @$_; $OPTIONS->{$opt} ? $flag : () } [ 'console', '-r' ], [ 'virtual', '-v' ], [ 'cmdb', '-d' ], [ 'backup', '-b' ], [ 'nic', '-n' ]; push @errors, "ERROR: Can only use one the following flags at a time: @conflicting\n" if @conflicting > 1; push @errors, "ERROR: Can't use flag -p without also specifying -d\n" if defined($OPTIONS->{policyid}) && !$OPTIONS->{cmdb}; push @errors, "ERROR: Can't use flag -c without also specifying -d\n" if $OPTIONS->{showcompliant} && !$OPTIONS->{cmdb}; push @errors, "ERROR: Can't use flag -s without also specifying -b\n" if $OPTIONS->{backuphistory} && !$OPTIONS->{backup}; push @errors, "ERROR: Can't use flag -m without also specifying -n\n" if defined($OPTIONS->{nicName}) && !$OPTIONS->{nic}; push @errors, "ERROR: Incorrect number of arguments\n" if @ARGV; usage(@errors) if @errors;
请注意,上面修复了代码中的大量错误。
的 帮助与使用错误 强>
--help
调用 HelpMessage 因此在两种情况下都是不正确的。
HelpMessage
创建以下子命名 usage 使用(不带参数)时 GetOptions 返回false,并在发生其他一些使用错误时显示错误消息:
usage
GetOptions
use File::Basename qw( basename ); sub usage { my $prog = basename($0); print STDERR $_ for @_; print STDERR "Try '$prog --help' for more information.\n"; exit(1); }
继续使用 HelpMessage 回应 --help ,但参数的默认值不适合 --help 。您应该使用以下内容:
'help' => sub { HelpMessage( -exitval => 0, -verbose => 1 ) },