使用Getopt :: Long检测不明确的选项

时间:2011-07-19 15:10:16

标签: perl options ambiguous getopt-long

使用Perl模块Getopt :: Long可以轻松检测不明确的选项吗?

例如:

#!/usr/bin/env perl

# test ambiguous options

use Getopt::Long;

my $hostname = 'localhost';

GetOptions( help         => sub { print "call usage sub here\n"; exit },
            'hostname=s' => \$hostname,
          );

print "hostname == '$hostname'\n";

默认情况下,Getopt :: Long支持唯一缩写。对于非唯一缩写,会抛出警告并且脚本继续以其快乐的方式。

./t.pl -h not_localhost

Option h is ambiguous (help, hostname)
hostname == 'localhost'

我希望我的脚本立即死于不明确的选项,以便立即通知,并防止它以意外的默认值运行。

1 个答案:

答案 0 :(得分:7)

GetOptions returns false表示失败。

尝试:

GetOptions( help         => sub { print "call usage sub here\n"; exit },
            'hostname=s' => \$hostname,
          )
    or die "You failed";

考虑善待您的用户并使用Pod::Usage。我自己的脚本通常看起来像这样:

use warnings;
use strict;
use Getopt::Long;
use Pod::Usage;
GetOptions(...)
    or pod2usage(2);

[actual code]

__END__
=head1 NAME
myscript.pl - My Awesome Script
=head1 SYNOPSYS
[etc.]
相关问题