是否有一种向脚本添加帮助功能的标准方法?最简单的方法可能是参数并打印一些文本,如果它是“-help”或其他东西。有没有人有关于如何做到这一点的任何例子?
谢谢!
答案 0 :(得分:11)
考虑Getopt::Long加Pod::Usage。我编写CLI工具的常用模式:
#!/usr/bin/env perl
# ABSTRACT: Short tool description
# PODNAME: toolname
use autodie;
use strict;
use utf8;
use warnings qw(all);
use Getopt::Long;
use Pod::Usage;
# VERSION
=head1 SYNOPSIS
toolname [options] files
=head1 DESCRIPTION
...
=cut
GetOptions(
q(help) => \my $help,
q(verbose) => \my $verbose,
) or pod2usage(q(-verbose) => 1);
pod2usage(q(-verbose) => 1) if $help;
# Actual code below
答案 1 :(得分:3)
易于使用:
if( $ARGV[0] eq '-h' || $ARGV[0] eq '-help')
{
help();
exit;
}
sub help { print "My help blah blah blah\n";
}
答案 2 :(得分:2)
看看https://github.com/qazwart/SVN-Watcher-Hook/blob/master/svn-watch.pl。我使用一种技术来组合Getopt::Long
模块和Pod::Usage
模块。
主要动作发生在第97至106行以及第108至110行。
Getopt::Long
是一个非常常用的模块,因为它可以轻松处理命令行参数。使用Pod文档很少见。但是,所有CPAN模块和所有内置模块的Perl都使用Pod文档,因此如果您不知道,learn it。 POD并不是很难学,它内置于Perl中,因此所有Perl程序都可以自我记录。您可以使用perldoc
命令打印出任何程序的POD文档。试试这个:
$ perldoc File::Find
您还可以使用pod2html
,pod2text
和其他类型的翻译命令将POD文档打印到HTML等中。
在我了解POD之前,我会把这样的东西放在我的程序顶部:
########################################################
# USAGE
#
my $USAGE =<<USAGE;
Usage:
foo [ -baz -fu <bar>] [-help]
where:
baz: yadda, yadda, yadda
fu: yadda, yadda, yadda
help: Prints out this helpful message
USAGE
#
######################################################
然后,在我的程序中,我可以这样做:
if ($help) {
print "$USAGE\n";
exit 0;
}
这样,有人可以查看代码并阅读使用文本。这也与使用-help
参数时打印出的文本相同。
答案 3 :(得分:0)
我这样做的方法是利用Getopt::Std
从命令行参数中查找-h
标志。
use strict;
use warnings;
use Getopt::Std;
my %args;
getopts('h', \%args);
my $help = "help goes here. You can use
more than one line to format the text";
die $help if $args{h};
# otherwise continue with script...
更复杂的方法是使用POD::usage
,虽然我没有亲自尝试过这种方式。