1 #############################################################################
2 # Pod/Usage.pm -- print usage messages for the running script.
4 # Copyright (C) 1996-1999 by Bradford Appleton. All rights reserved.
5 # This file is part of "PodParser". PodParser is free software;
6 # you can redistribute it and/or modify it under the same terms
8 #############################################################################
12 use vars qw($VERSION);
13 $VERSION = 1.090; ## Current version of this package
14 require 5.004; ## requires this Perl version or later
18 Pod::Usage, pod2usage() - print a usage message from embedded pod documentation
24 my $message_text = "This text precedes the usage message.";
25 my $exit_status = 2; ## The exit status to use
26 my $verbose_level = 0; ## The verbose level to use
27 my $filehandle = \*STDERR; ## The filehandle to write to
29 pod2usage($message_text);
31 pod2usage($exit_status);
33 pod2usage( { -message => $message_text ,
34 -exitval => $exit_status ,
35 -verbose => $verbose_level,
36 -output => $filehandle } );
38 pod2usage( -msg => $message_text ,
39 -exitval => $exit_status ,
40 -verbose => $verbose_level,
41 -output => $filehandle );
45 B<pod2usage> should be given either a single argument, or a list of
46 arguments corresponding to an associative array (a "hash"). When a single
47 argument is given, it should correspond to exactly one of the following:
53 A string containing the text of a message to print I<before> printing
58 A numeric value corresponding to the desired exit status
66 If more than one argument is given then the entire argument list is
67 assumed to be a hash. If a hash is supplied (either as a reference or
68 as a list) it should contain one or more elements with the following
77 The text of a message to print immediately prior to printing the
78 program's usage message.
82 The desired exit status to pass to the B<exit()> function.
86 The desired level of "verboseness" to use when printing the usage
87 message. If the corresponding value is 0, then only the "SYNOPSIS"
88 section of the pod documentation is printed. If the corresponding value
89 is 1, then the "SYNOPSIS" section, along with any section entitled
90 "OPTIONS", "ARGUMENTS", or "OPTIONS AND ARGUMENTS" is printed. If the
91 corresponding value is 2 or more then the entire manpage is printed.
95 A reference to a filehandle, or the pathname of a file to which the
96 usage message should be written. The default is C<\*STDERR> unless the
97 exit value is less than 2 (in which case the default is C<\*STDOUT>).
101 A reference to a filehandle, or the pathname of a file from which the
102 invoking script's pod documentation should be read. It defaults to the
103 file indicated by C<$0> (C<$PROGRAM_NAME> for users of F<English.pm>).
107 A list of directory paths. If the input file does not exist, then it
108 will be searched for in the given directory list (in the order the
109 directories appear in the list). It defaults to the list of directories
110 implied by C<$ENV{PATH}>. The list may be specified either by a reference
111 to an array, or by a string of directory paths which use the same path
112 separator as C<$ENV{PATH}> on your system (e.g., C<:> for Unix, C<;> for
119 B<pod2usage> will print a usage message for the invoking script (using
120 its embedded pod documentation) and then exit the script with the
121 desired exit status. The usage message printed may have any one of three
122 levels of "verboseness": If the verbose level is 0, then only a synopsis
123 is printed. If the verbose level is 1, then the synopsis is printed
124 along with a description (if present) of the command line options and
125 arguments. If the verbose level is 2, then the entire manual page is
128 Unless they are explicitly specified, the default values for the exit
129 status, verbose level, and output stream to use are determined as
136 If neither the exit status nor the verbose level is specified, then the
137 default is to use an exit status of 2 with a verbose level of 0.
141 If an exit status I<is> specified but the verbose level is I<not>, then the
142 verbose level will default to 1 if the exit status is less than 2 and
143 will default to 0 otherwise.
147 If an exit status is I<not> specified but verbose level I<is> given, then
148 the exit status will default to 2 if the verbose level is 0 and will
149 default to 1 otherwise.
153 If the exit status used is less than 2, then output is printed on
154 C<STDOUT>. Otherwise output is printed on C<STDERR>.
158 Although the above may seem a bit confusing at first, it generally does
159 "the right thing" in most situations. This determination of the default
160 values to use is based upon the following typical Unix conventions:
166 An exit status of 0 implies "success". For example, B<diff(1)> exits
167 with a status of 0 if the two files have the same contents.
171 An exit status of 1 implies possibly abnormal, but non-defective, program
172 termination. For example, B<grep(1)> exits with a status of 1 if
173 it did I<not> find a matching line for the given regular expression.
177 An exit status of 2 or more implies a fatal error. For example, B<ls(1)>
178 exits with a status of 2 if you specify an illegal (unknown) option on
183 Usage messages issued as a result of bad command-line syntax should go
184 to C<STDERR>. However, usage messages issued due to an explicit request
185 to print usage (like specifying B<-help> on the command line) should go
186 to C<STDOUT>, just in case the user wants to pipe the output to a pager
187 (such as B<more(1)>).
191 If program usage has been explicitly requested by the user, it is often
192 desireable to exit with a status of 1 (as opposed to 0) after issuing
193 the user-requested usage message. It is also desireable to give a
194 more verbose description of program usage in this case.
198 B<pod2usage> doesn't force the above conventions upon you, but it will
199 use them by default if you don't expressly tell it to do otherwise. The
200 ability of B<pod2usage()> to accept a single number or a string makes it
201 convenient to use as an innocent looking error message handling function:
207 GetOptions("help", "man", "flag1") || pod2usage(2);
208 pod2usage(1) if ($opt_help);
209 pod2usage(-verbose => 2) if ($opt_man);
211 ## Check for too many filenames
212 pod2usage("$0: Too many files given.\n") if (@ARGV > 1);
214 Some user's however may feel that the above "economy of expression" is
215 not particularly readable nor consistent and may instead choose to do
216 something more like the following:
222 GetOptions("help", "man", "flag1") || pod2usage(-verbose => 0);
223 pod2usage(-verbose => 1) if ($opt_help);
224 pod2usage(-verbose => 2) if ($opt_man);
226 ## Check for too many filenames
227 pod2usage(-verbose => 2, -message => "$0: Too many files given.\n")
230 As with all things in Perl, I<there's more than one way to do it>, and
231 B<pod2usage()> adheres to this philosophy. If you are interested in
232 seeing a number of different ways to invoke B<pod2usage> (although by no
233 means exhaustive), please refer to L<"EXAMPLES">.
237 Each of the following invocations of C<pod2usage()> will print just the
238 "SYNOPSIS" section to C<STDERR> and will exit with a status of 2:
244 pod2usage(-verbose => 0);
246 pod2usage(-exitval => 2);
248 pod2usage({-exitval => 2, -output => \*STDERR});
250 pod2usage({-verbose => 0, -output => \*STDERR});
252 pod2usage(-exitval => 2, -verbose => 0);
254 pod2usage(-exitval => 2, -verbose => 0, -output => \*STDERR);
256 Each of the following invocations of C<pod2usage()> will print a message
257 of "Syntax error." (followed by a newline) to C<STDERR>, immediately
258 followed by just the "SYNOPSIS" section (also printed to C<STDERR>) and
259 will exit with a status of 2:
261 pod2usage("Syntax error.");
263 pod2usage(-message => "Syntax error.", -verbose => 0);
265 pod2usage(-msg => "Syntax error.", -exitval => 2);
267 pod2usage({-msg => "Syntax error.", -exitval => 2, -output => \*STDERR});
269 pod2usage({-msg => "Syntax error.", -verbose => 0, -output => \*STDERR});
271 pod2usage(-msg => "Syntax error.", -exitval => 2, -verbose => 0);
273 pod2usage(-message => "Syntax error.",
276 -output => \*STDERR);
278 Each of the following invocations of C<pod2usage()> will print the
279 "SYNOPSIS" section and any "OPTIONS" and/or "ARGUMENTS" sections to
280 C<STDOUT> and will exit with a status of 1:
284 pod2usage(-verbose => 1);
286 pod2usage(-exitval => 1);
288 pod2usage({-exitval => 1, -output => \*STDOUT});
290 pod2usage({-verbose => 1, -output => \*STDOUT});
292 pod2usage(-exitval => 1, -verbose => 1);
294 pod2usage(-exitval => 1, -verbose => 1, -output => \*STDOUT});
296 Each of the following invocations of C<pod2usage()> will print the
297 entire manual page to C<STDOUT> and will exit with a status of 1:
299 pod2usage(-verbose => 2);
301 pod2usage({-verbose => 2, -output => \*STDOUT});
303 pod2usage(-exitval => 1, -verbose => 2);
305 pod2usage({-exitval => 1, -verbose => 2, -output => \*STDOUT});
307 =head2 Recommended Use
309 Most scripts should print some type of usage message to C<STDERR> when a
310 command line syntax error is detected. They should also provide an
311 option (usually C<-H> or C<-help>) to print a (possibly more verbose)
312 usage message to C<STDOUT>. Some scripts may even wish to go so far as to
313 provide a means of printing their complete documentation to C<STDOUT>
314 (perhaps by allowing a C<-man> option). The following example uses
315 B<Pod::Usage> in combination with B<Getopt::Long> to do all of these
321 ## Parse options and print usage if there is a syntax error,
322 ## or if usage was explicitly requested.
323 GetOptions("help", "man", "flag1") || pod2usage(2);
324 pod2usage(1) if ($opt_help);
325 pod2usage(-verbose => 2) if ($opt_man);
327 ## If no arguments were given, then allow STDIN to be used only
328 ## if it's not connected to a terminal (otherwise print usage)
329 pod2usage("$0: No files given.") if ((@ARGV == 0) && (-t STDIN));
333 By default, B<pod2usage()> will use C<$0> as the path to the pod input
334 file. Unfortunately, not all systems on which Perl runs will set C<$0>
335 properly (although if C<$0> isn't found, B<pod2usage()> will search
336 C<$ENV{PATH}> or else the list specified by the C<-pathlist> option).
337 If this is the case for your system, you may need to explicitly specify
338 the path to the pod docs for the invoking script using something
339 similar to the following:
341 pod2usage(-exitval => 2, -input => "/path/to/your/pod/docs");
345 Brad Appleton E<lt>bradapp@enteract.comE<gt>
347 Based on code for B<Pod::Text::pod2text()> written by
348 Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>
350 =head1 ACKNOWLEDGEMENTS
352 Steven McDougall E<lt>swmcd@world.std.comE<gt> for his help and patience
353 with re-writing this manpage.
357 #############################################################################
365 use vars qw(@ISA @EXPORT);
366 @EXPORT = qw(&pod2usage);
368 if ( $] >= 5.005_58 ) {
370 @ISA = qw( Pod::Text );
373 require Pod::PlainText;
374 @ISA = qw( Pod::PlainText );
379 ##---------------------------------------------------------------------------
381 ##---------------------------------
382 ## Function definitions begin here
383 ##---------------------------------
386 local($_) = shift || "";
390 ## Too many arguments - assume that this is a hash and
391 ## the user forgot to pass a reference to it.
395 ## User passed a ref to a hash
396 %opts = %{$_} if (ref($_) eq 'HASH');
398 elsif (/^[-+]?\d+$/) {
399 ## User passed in the exit value to use
400 $opts{"-exitval"} = $_;
403 ## User passed in a message to print before issuing usage.
404 $_ and $opts{"-message"} = $_;
407 ## Need this for backward compatibility since we formerly used
408 ## options that were all uppercase words rather than ones that
409 ## looked like Unix command-line options.
410 ## to be uppercase keywords)
414 /^-msg/i and $_ = '-message';
415 /^-exit/i and $_ = '-exitval';
419 ## Now determine default -exitval and -verbose values to use
420 if ((! defined $opts{"-exitval"}) && (! defined $opts{"-verbose"})) {
421 $opts{"-exitval"} = 2;
422 $opts{"-verbose"} = 0;
424 elsif (! defined $opts{"-exitval"}) {
425 $opts{"-exitval"} = ($opts{"-verbose"} > 0) ? 1 : 2;
427 elsif (! defined $opts{"-verbose"}) {
428 $opts{"-verbose"} = ($opts{"-exitval"} < 2);
431 ## Default the output file
432 $opts{"-output"} = ($opts{"-exitval"} < 2) ? \*STDOUT : \*STDERR
433 unless (defined $opts{"-output"});
434 ## Default the input file
435 $opts{"-input"} = $0 unless (defined $opts{"-input"});
437 ## Look up input file in path if it doesnt exist.
438 unless ((ref $opts{"-input"}) || (-e $opts{"-input"})) {
439 my ($dirname, $basename) = ('', $opts{"-input"});
440 my $pathsep = ($^O =~ /^(?:dos|os2|MSWin32)$/) ? ";"
441 : (($^O eq 'MacOS') ? ',' : ":");
442 my $pathspec = $opts{"-pathlist"} || $ENV{PATH} || $ENV{PERL5LIB};
444 my @paths = (ref $pathspec) ? @$pathspec : split($pathsep, $pathspec);
445 for $dirname (@paths) {
446 $_ = File::Spec->catfile($dirname, $basename) if length;
447 last if (-e $_) && ($opts{"-input"} = $_);
451 ## Now create a pod reader and constrain it to the desired sections.
452 my $parser = new Pod::Usage(USAGE_OPTIONS => \%opts);
453 if ($opts{"-verbose"} == 0) {
454 $parser->select("SYNOPSIS");
456 elsif ($opts{"-verbose"} == 1) {
457 my $opt_re = '(?i)' .
458 '(?:OPTIONS|ARGUMENTS)' .
459 '(?:\s*(?:AND|\/)\s*(?:OPTIONS|ARGUMENTS))?';
460 $parser->select( 'SYNOPSIS', $opt_re, "DESCRIPTION/$opt_re" );
463 ## Now translate the pod document and then exit with the desired status
464 $parser->parse_from_file($opts{"-input"}, $opts{"-output"});
465 exit($opts{"-exitval"});
468 ##---------------------------------------------------------------------------
470 ##-------------------------------
471 ## Method definitions begin here
472 ##-------------------------------
476 my $class = ref($this) || $this;
478 my $self = {%params};
486 $self->SUPER::begin_pod(); ## Have to call superclass
487 my $msg = $self->{USAGE_OPTIONS}->{-message} or return 1;
488 my $out_fh = $self->output_handle();
489 print $out_fh "$msg\n";
492 sub preprocess_paragraph {
496 ## See if this is a heading and we arent printing the entire manpage.
497 if (($self->{USAGE_OPTIONS}->{-verbose} < 2) && /^=head/) {
498 ## Change the title of the SYNOPSIS section to USAGE
499 s/^=head1\s+SYNOPSIS\s*$/=head1 USAGE/;
500 ## Try to do some lowercasing instead of all-caps in headings
501 s{([A-Z])([A-Z]+)}{((length($2) > 2) ? $1 : lc($1)) . lc($2)}ge;
502 ## Use a colon to end all headings
503 s/\s*$/:/ unless (/:\s*$/);
506 return $self->SUPER::preprocess_paragraph($_);