如何使用Getopt :: Std响应--help标志?

时间:2014-02-22 15:53:45

标签: perl options getopt

我希望我的脚本在使用--help命令行选项运行时打印帮助消息。基于Getopt::Std documentation,此子应该可以解决问题:

#!/usr/bin/env perl
use strict;
use warnings;
use 5.014;
use Getopt::Std;

sub HELP_MESSAGE {
    say "HELP MESSAGE";
}

但它什么都没打印。出于好奇,我还尝试添加这个:

for (@ARGV) {
    HELP_MESSAGE() if /--help/;
}

它确实有效,但似乎相当草率。我知道使用-h标志会非常简单,但我想同时拥有它们。

1 个答案:

答案 0 :(得分:4)

documentation of Getopt::Std

  

如果-不是公认的切换字母, getopts() 支持参数--help--version。如果定义了main::HELP_MESSAGE()和/或main::VERSION_MESSAGE(),则会调用它们; ...

所以试试这个:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.014;
use Getopt::Std;

$Getopt::Std::STANDARD_HELP_VERSION = 1;
our $VERSION = 0.1;

getopts('');       # <<< You forgot this line, and `getopt()` DOES NOT work

sub HELP_MESSAGE {
    say "HELP MESSAGE";
}

试运行:

$ ./t00.pl --help
./t00.pl version 0.1 calling Getopt::Std::getopts (version 1.07),
running under Perl version 5.16.3.
HELP MESSAGE