我希望我的脚本在使用命令行选项运行时打印帮助消息--help
。根据Getopt::Std
文档,这个子程序应该可以解决问题:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.014;
use Getopt::Std;
sub HELP_MESSAGE {
say "HELP MESSAGE";
}
Run Code Online (Sandbox Code Playgroud)
但它什么也没打印。出于好奇,我也尝试添加这个:
for (@ARGV) {
HELP_MESSAGE() if /--help/;
}
Run Code Online (Sandbox Code Playgroud)
它确实有效,但看起来相当草率。我知道使用该-h
标志非常简单,但我想两者都拥有。
如果
-
不是可识别的开关字母,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";
}
Run Code Online (Sandbox Code Playgroud)
测试运行:
$ ./t00.pl --help
./t00.pl version 0.1 calling Getopt::Std::getopts (version 1.07),
running under Perl version 5.16.3.
HELP MESSAGE
Run Code Online (Sandbox Code Playgroud)