4

有没有一种简单的方法可以使用 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'

我希望我的脚本在立即通知的模棱两可的选项上立即终止,并防止它以意外的默认值运行。

4

1 回答 1

7

GetOptions返回 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.]
于 2011-07-19T15:23:45.837 回答