How to print program usage in Perl?
What's the easiest to maintain way of printing a Perl program's usage to stdout? I am looking for he开发者_JAVA百科redoc tricks or anything similarly useful. Forget individual successive prints.
EDIT 1: the issue I have faced many times is to have to maintain usage, general script documentation and option processing separately. I was looking for a way to combine some or all of this with minimal overhead. Thanks for the many suggestions. I will accept an answer when I have an opportunity to experiment proposed solutions.
Pod::Usage
maybe? This was suggested by GetOpt::Long
.
Getopt::Std::WithCheck
allows you to combine the definition of options along a description, and Getopt::Simple
does the same.
I think you just answered your own question. A heredoc clause is the usual way to go, if the usage information is not automatically generated (e.g. by Getopt::Long::Descriptive or MooseX::Getopt).
package ClassA;
use Getopt::Long::Descriptive;
my ($opt, $usage) = describe_options(
'my-program %o <some-arg>',
[ 'server|s=s', "the server to connect to" ],
[ 'port|p=i', "the port to connect to", { default => 79 } ],
[],
[ 'verbose|v', "print extra stuff" ],
[ 'help', "print usage message and exit" ],
);
print($usage->text), exit if $opt->help;
package ClassB;
use Moose;
with' MooseX::Getopt';
has server => (
is => 'ro', isa => 'Str',
traits => [ 'Getopt' ],
cmd_aliases => ['s'],
documentation => 'the server to connect to',
);
has port => (
is => 'ro', isa => 'Int',
traits => [ 'Getopt' ],
cmd_aliases => ['p'],
default => 79,
documentation => 'the port to connect to',
);
has verbose => (
is => 'ro', isa => 'Bool',
traits => [ 'Getopt' ],
cmd_aliases => ['v'],
documentation => 'print extra stuff',
);
You can call ClassB like so (if you're not using MooseX::Runnable or a script to construct the object):
perl -I. -MClassB -wle'my $obj = ClassB->new_with_options;' -- --help
And produces:
usage: -e [-?psv] [long options...] -? --usage --help Prints this usage information. -s --server the server to connect to -p --port the port to connect to -v --verbose print extra stuff
something like :
print <<END;
Usage : foo bar
Foobar foobar.
END
?
Damian Conway has two interesting modules that use the documentation of your command-line interface to produce the parsing code:
- Getopt::Euclid: declare your interface in the POD
- Getopt::Declare: declare your interface in a string that you can output in case of error
They will help (force) you to maintain a documentation matching the code.
You can use a here-doc :
use Getopt::Long;
my $USAGE = <<"USAGE";
Usage: some_script.pl -env=[dev|qa|pr]
Regular options:
-env -- Valid values for env are 'dev', 'qa', 'pr'
USAGE
our ($opt_env);
die $USAGE
unless GetOptions ("env=s" => \$opt_env); # string
精彩评论