【问题标题】:Detecting ambiguous options with Getopt::Long使用 Getopt::Long 检测不明确的选项
【发布时间】:2011-07-19 15:10:16
【问题描述】:

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

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

【问题讨论】:

    标签: perl options ambiguous getopt-long


    【解决方案1】:

    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.]
    

    【讨论】:

    • 谢谢!尽管不检查返回值我觉得非常愚蠢,但我非常感谢您的快速响应和 Pod 建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2011-01-14
    • 1970-01-01
    相关资源
    最近更新 更多