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

标签 perl options getopt

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

#!/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 标志会很简单,但我想同时拥有。

最佳答案

documentation of Getopt::Std

If - is not a recognized switch letter, getopts() supports arguments --help and --version. If main::HELP_MESSAGE() and/or main::VERSION_MESSAGE() are defined, they are called; ...



所以试试这个:
#!/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

关于perl - 如何使用 Getopt::Std 响应 --help 标志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21956620/

相关文章:

perl - 为 Perl 脚本传递命令行参数以及来自 STDIN 的输入?

perl - 如何从命令行使用 ActivePerl 的 PPM 4?

perl - 等待子进程超时

c - 如何在C中创建基于字母的选项

c - 使用函数 getopt 得到除数的个数

perl - perl 中的 $ENV{$variable}

compiler-errors - 更改续行限制的 Fortran 77 选项出现问题

C - 检查主要参数

c++ - optarg 设置为空

c - 在 C 中使用 getopt_long 将参数传递给函数