1 #############################################################################
2 # Pod/Usage.pm -- print usage messages for the running script.
4 # Copyright (C) 1996-2000 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.33; ## Current version of this package
14 require 5.005; ## 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 );
43 pod2usage( -verbose => 2,
48 B<pod2usage> should be given either a single argument, or a list of
49 arguments corresponding to an associative array (a "hash"). When a single
50 argument is given, it should correspond to exactly one of the following:
56 A string containing the text of a message to print I<before> printing
61 A numeric value corresponding to the desired exit status
69 If more than one argument is given then the entire argument list is
70 assumed to be a hash. If a hash is supplied (either as a reference or
71 as a list) it should contain one or more elements with the following
80 The text of a message to print immediately prior to printing the
81 program's usage message.
85 The desired exit status to pass to the B<exit()> function.
86 This should be an integer, or else the string "NOEXIT" to
87 indicate that control should simply be returned without
88 terminating the invoking process.
92 The desired level of "verboseness" to use when printing the usage
93 message. If the corresponding value is 0, then only the "SYNOPSIS"
94 section of the pod documentation is printed. If the corresponding value
95 is 1, then the "SYNOPSIS" section, along with any section entitled
96 "OPTIONS", "ARGUMENTS", or "OPTIONS AND ARGUMENTS" is printed. If the
97 corresponding value is 2 or more then the entire manpage is printed.
99 The special verbosity level 99 requires to also specify the -section
100 parameter; then these sections are extracted (see L<Pod::Select>)
105 A string representing a selection list for sections to be printed
106 when -verbose is set to 99, e.g. C<"NAME|SYNOPSIS|DESCRIPTION|VERSION">.
110 A reference to a filehandle, or the pathname of a file to which the
111 usage message should be written. The default is C<\*STDERR> unless the
112 exit value is less than 2 (in which case the default is C<\*STDOUT>).
116 A reference to a filehandle, or the pathname of a file from which the
117 invoking script's pod documentation should be read. It defaults to the
118 file indicated by C<$0> (C<$PROGRAM_NAME> for users of F<English.pm>).
122 A list of directory paths. If the input file does not exist, then it
123 will be searched for in the given directory list (in the order the
124 directories appear in the list). It defaults to the list of directories
125 implied by C<$ENV{PATH}>. The list may be specified either by a reference
126 to an array, or by a string of directory paths which use the same path
127 separator as C<$ENV{PATH}> on your system (e.g., C<:> for Unix, C<;> for
132 By default, Pod::Usage will call L<perldoc> when -verbose >= 2 is
133 specified. This does not work well e.g. if the script was packed
134 with L<PAR>. The -noperldoc option suppresses the external call to
135 L<perldoc> and uses the simple text formatter (L<Pod::Text>) to
142 B<pod2usage> will print a usage message for the invoking script (using
143 its embedded pod documentation) and then exit the script with the
144 desired exit status. The usage message printed may have any one of three
145 levels of "verboseness": If the verbose level is 0, then only a synopsis
146 is printed. If the verbose level is 1, then the synopsis is printed
147 along with a description (if present) of the command line options and
148 arguments. If the verbose level is 2, then the entire manual page is
151 Unless they are explicitly specified, the default values for the exit
152 status, verbose level, and output stream to use are determined as
159 If neither the exit status nor the verbose level is specified, then the
160 default is to use an exit status of 2 with a verbose level of 0.
164 If an exit status I<is> specified but the verbose level is I<not>, then the
165 verbose level will default to 1 if the exit status is less than 2 and
166 will default to 0 otherwise.
170 If an exit status is I<not> specified but verbose level I<is> given, then
171 the exit status will default to 2 if the verbose level is 0 and will
172 default to 1 otherwise.
176 If the exit status used is less than 2, then output is printed on
177 C<STDOUT>. Otherwise output is printed on C<STDERR>.
181 Although the above may seem a bit confusing at first, it generally does
182 "the right thing" in most situations. This determination of the default
183 values to use is based upon the following typical Unix conventions:
189 An exit status of 0 implies "success". For example, B<diff(1)> exits
190 with a status of 0 if the two files have the same contents.
194 An exit status of 1 implies possibly abnormal, but non-defective, program
195 termination. For example, B<grep(1)> exits with a status of 1 if
196 it did I<not> find a matching line for the given regular expression.
200 An exit status of 2 or more implies a fatal error. For example, B<ls(1)>
201 exits with a status of 2 if you specify an illegal (unknown) option on
206 Usage messages issued as a result of bad command-line syntax should go
207 to C<STDERR>. However, usage messages issued due to an explicit request
208 to print usage (like specifying B<-help> on the command line) should go
209 to C<STDOUT>, just in case the user wants to pipe the output to a pager
210 (such as B<more(1)>).
214 If program usage has been explicitly requested by the user, it is often
215 desireable to exit with a status of 1 (as opposed to 0) after issuing
216 the user-requested usage message. It is also desireable to give a
217 more verbose description of program usage in this case.
221 B<pod2usage> doesn't force the above conventions upon you, but it will
222 use them by default if you don't expressly tell it to do otherwise. The
223 ability of B<pod2usage()> to accept a single number or a string makes it
224 convenient to use as an innocent looking error message handling function:
230 GetOptions("help", "man", "flag1") || pod2usage(2);
231 pod2usage(1) if ($opt_help);
232 pod2usage(-verbose => 2) if ($opt_man);
234 ## Check for too many filenames
235 pod2usage("$0: Too many files given.\n") if (@ARGV > 1);
237 Some user's however may feel that the above "economy of expression" is
238 not particularly readable nor consistent and may instead choose to do
239 something more like the following:
245 GetOptions("help", "man", "flag1") || pod2usage(-verbose => 0);
246 pod2usage(-verbose => 1) if ($opt_help);
247 pod2usage(-verbose => 2) if ($opt_man);
249 ## Check for too many filenames
250 pod2usage(-verbose => 2, -message => "$0: Too many files given.\n")
253 As with all things in Perl, I<there's more than one way to do it>, and
254 B<pod2usage()> adheres to this philosophy. If you are interested in
255 seeing a number of different ways to invoke B<pod2usage> (although by no
256 means exhaustive), please refer to L<"EXAMPLES">.
260 Each of the following invocations of C<pod2usage()> will print just the
261 "SYNOPSIS" section to C<STDERR> and will exit with a status of 2:
267 pod2usage(-verbose => 0);
269 pod2usage(-exitval => 2);
271 pod2usage({-exitval => 2, -output => \*STDERR});
273 pod2usage({-verbose => 0, -output => \*STDERR});
275 pod2usage(-exitval => 2, -verbose => 0);
277 pod2usage(-exitval => 2, -verbose => 0, -output => \*STDERR);
279 Each of the following invocations of C<pod2usage()> will print a message
280 of "Syntax error." (followed by a newline) to C<STDERR>, immediately
281 followed by just the "SYNOPSIS" section (also printed to C<STDERR>) and
282 will exit with a status of 2:
284 pod2usage("Syntax error.");
286 pod2usage(-message => "Syntax error.", -verbose => 0);
288 pod2usage(-msg => "Syntax error.", -exitval => 2);
290 pod2usage({-msg => "Syntax error.", -exitval => 2, -output => \*STDERR});
292 pod2usage({-msg => "Syntax error.", -verbose => 0, -output => \*STDERR});
294 pod2usage(-msg => "Syntax error.", -exitval => 2, -verbose => 0);
296 pod2usage(-message => "Syntax error.",
299 -output => \*STDERR);
301 Each of the following invocations of C<pod2usage()> will print the
302 "SYNOPSIS" section and any "OPTIONS" and/or "ARGUMENTS" sections to
303 C<STDOUT> and will exit with a status of 1:
307 pod2usage(-verbose => 1);
309 pod2usage(-exitval => 1);
311 pod2usage({-exitval => 1, -output => \*STDOUT});
313 pod2usage({-verbose => 1, -output => \*STDOUT});
315 pod2usage(-exitval => 1, -verbose => 1);
317 pod2usage(-exitval => 1, -verbose => 1, -output => \*STDOUT});
319 Each of the following invocations of C<pod2usage()> will print the
320 entire manual page to C<STDOUT> and will exit with a status of 1:
322 pod2usage(-verbose => 2);
324 pod2usage({-verbose => 2, -output => \*STDOUT});
326 pod2usage(-exitval => 1, -verbose => 2);
328 pod2usage({-exitval => 1, -verbose => 2, -output => \*STDOUT});
330 =head2 Recommended Use
332 Most scripts should print some type of usage message to C<STDERR> when a
333 command line syntax error is detected. They should also provide an
334 option (usually C<-H> or C<-help>) to print a (possibly more verbose)
335 usage message to C<STDOUT>. Some scripts may even wish to go so far as to
336 provide a means of printing their complete documentation to C<STDOUT>
337 (perhaps by allowing a C<-man> option). The following complete example
338 uses B<Pod::Usage> in combination with B<Getopt::Long> to do all of these
346 ## Parse options and print usage if there is a syntax error,
347 ## or if usage was explicitly requested.
348 GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
349 pod2usage(1) if $help;
350 pod2usage(-verbose => 2) if $man;
352 ## If no arguments were given, then allow STDIN to be used only
353 ## if it's not connected to a terminal (otherwise print usage)
354 pod2usage("$0: No files given.") if ((@ARGV == 0) && (-t STDIN));
359 sample - Using GetOpt::Long and Pod::Usage
363 sample [options] [file ...]
366 -help brief help message
367 -man full documentation
375 Print a brief help message and exits.
379 Prints the manual page and exits.
385 B<This program> will read the given input file(s) and do something
386 useful with the contents thereof.
392 By default, B<pod2usage()> will use C<$0> as the path to the pod input
393 file. Unfortunately, not all systems on which Perl runs will set C<$0>
394 properly (although if C<$0> isn't found, B<pod2usage()> will search
395 C<$ENV{PATH}> or else the list specified by the C<-pathlist> option).
396 If this is the case for your system, you may need to explicitly specify
397 the path to the pod docs for the invoking script using something
398 similar to the following:
400 pod2usage(-exitval => 2, -input => "/path/to/your/pod/docs");
402 In the pathological case that a script is called via a relative path
403 I<and> the script itself changes the current working directory
404 (see L<perlfunc/chdir>) I<before> calling pod2usage, Pod::Usage will
405 fail even on robust platforms. Don't do that.
409 Please report bugs using L<http://rt.cpan.org>.
411 Brad Appleton E<lt>bradapp@enteract.comE<gt>
413 Based on code for B<Pod::Text::pod2text()> written by
414 Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>
416 =head1 ACKNOWLEDGEMENTS
418 Steven McDougall E<lt>swmcd@world.std.comE<gt> for his help and patience
419 with re-writing this manpage.
423 #############################################################################
432 use vars qw(@ISA @EXPORT);
433 @EXPORT = qw(&pod2usage);
435 if ( $] >= 5.005_58
) {
437 @ISA = qw( Pod::Text );
440 require Pod
::PlainText
;
441 @ISA = qw( Pod::PlainText );
446 ##---------------------------------------------------------------------------
448 ##---------------------------------
449 ## Function definitions begin here
450 ##---------------------------------
457 ## Too many arguments - assume that this is a hash and
458 ## the user forgot to pass a reference to it.
461 elsif (!defined $_) {
465 ## User passed a ref to a hash
466 %opts = %{$_} if (ref($_) eq 'HASH');
468 elsif (/^[-+]?\d+$/) {
469 ## User passed in the exit value to use
470 $opts{"-exitval"} = $_;
473 ## User passed in a message to print before issuing usage.
474 $_ and $opts{"-message"} = $_;
477 ## Need this for backward compatibility since we formerly used
478 ## options that were all uppercase words rather than ones that
479 ## looked like Unix command-line options.
480 ## to be uppercase keywords)
484 /^-msg/i and $_ = '-message';
485 /^-exit/i and $_ = '-exitval';
489 ## Now determine default -exitval and -verbose values to use
490 if ((! defined $opts{"-exitval"}) && (! defined $opts{"-verbose"})) {
491 $opts{"-exitval"} = 2;
492 $opts{"-verbose"} = 0;
494 elsif (! defined $opts{"-exitval"}) {
495 $opts{"-exitval"} = ($opts{"-verbose"} > 0) ?
1 : 2;
497 elsif (! defined $opts{"-verbose"}) {
498 $opts{"-verbose"} = (lc($opts{"-exitval"}) eq "noexit" ||
499 $opts{"-exitval"} < 2);
502 ## Default the output file
503 $opts{"-output"} = (lc($opts{"-exitval"}) eq "noexit" ||
504 $opts{"-exitval"} < 2) ? \
*STDOUT
: \
*STDERR
505 unless (defined $opts{"-output"});
506 ## Default the input file
507 $opts{"-input"} = $0 unless (defined $opts{"-input"});
509 ## Look up input file in path if it doesnt exist.
510 unless ((ref $opts{"-input"}) || (-e
$opts{"-input"})) {
511 my ($dirname, $basename) = ('', $opts{"-input"});
512 my $pathsep = ($^O
=~ /^(?:dos|os2|MSWin32)$/) ?
";"
513 : (($^O
eq 'MacOS' || $^O
eq 'VMS') ?
',' : ":");
514 my $pathspec = $opts{"-pathlist"} || $ENV{PATH
} || $ENV{PERL5LIB
};
516 my @paths = (ref $pathspec) ? @
$pathspec : split($pathsep, $pathspec);
517 for $dirname (@paths) {
518 $_ = File
::Spec
->catfile($dirname, $basename) if length;
519 last if (-e
$_) && ($opts{"-input"} = $_);
523 ## Now create a pod reader and constrain it to the desired sections.
524 my $parser = new Pod
::Usage
(USAGE_OPTIONS
=> \
%opts);
525 if ($opts{"-verbose"} == 0) {
526 $parser->select('SYNOPSIS\s*');
528 elsif ($opts{"-verbose"} == 1) {
529 my $opt_re = '(?i)' .
530 '(?:OPTIONS|ARGUMENTS)' .
531 '(?:\s*(?:AND|\/)\s*(?:OPTIONS|ARGUMENTS))?';
532 $parser->select( 'SYNOPSIS', $opt_re, "DESCRIPTION/$opt_re" );
534 elsif ($opts{"-verbose"} == 99) {
535 $parser->select( $opts{"-sections"} );
536 $opts{"-verbose"} = 1;
539 ## Now translate the pod document and then exit with the desired status
540 if ( !$opts{"-noperldoc"}
541 and $opts{"-verbose"} >= 2
542 and !ref($opts{"-input"})
543 and $opts{"-output"} == \
*STDOUT
)
545 ## spit out the entire PODs. Might as well invoke perldoc
546 my $progpath = File
::Spec
->catfile($Config{scriptdir
}, "perldoc");
547 system($progpath, $opts{"-input"});
550 $parser->parse_from_file($opts{"-input"}, $opts{"-output"});
553 exit($opts{"-exitval"}) unless (lc($opts{"-exitval"}) eq 'noexit');
556 ##---------------------------------------------------------------------------
558 ##-------------------------------
559 ## Method definitions begin here
560 ##-------------------------------
564 my $class = ref($this) || $this;
566 my $self = {%params};
568 if ($self->can('initialize')) {
571 $self = $self->SUPER::new
();
572 %$self = (%$self, %params);
578 my ($self, @res) = @_;
579 if ($ISA[0]->can('select')) {
580 $self->SUPER::select(@_);
582 $self->{USAGE_SELECT
} = \
@res;
586 # Override Pod::Text->seq_i to return just "arg", not "*arg*".
587 sub seq_i
{ return $_[1] }
589 # This overrides the Pod::Text method to do something very akin to what
590 # Pod::Select did as well as the work done below by preprocess_paragraph.
591 # Note that the below is very, very specific to Pod::Text.
592 sub _handle_element_end
{
593 my ($self, $element) = @_;
594 if ($element eq 'head1') {
595 $$self{USAGE_HEAD1
} = $$self{PENDING
}[-1][1];
596 $$self{PENDING
}[-1][1] =~ s/^\s*SYNOPSIS\s*$/USAGE/;
597 } elsif ($element eq 'head2') {
598 $$self{USAGE_HEAD2
} = $$self{PENDING
}[-1][1];
600 if ($element eq 'head1' || $element eq 'head2') {
601 $$self{USAGE_SKIPPING
} = 1;
602 my $heading = $$self{USAGE_HEAD1
};
603 $heading .= '/' . $$self{USAGE_HEAD2
} if defined $$self{USAGE_HEAD2
};
604 for (@
{ $$self{USAGE_SELECT
} }) {
605 if ($heading =~ /^$_\s*$/) {
606 $$self{USAGE_SKIPPING
} = 0;
611 # Try to do some lowercasing instead of all-caps in headings, and use
612 # a colon to end all headings.
613 local $_ = $$self{PENDING
}[-1][1];
614 s{([A-Z])([A-Z]+)}{((length($2) > 2) ? $1 : lc($1)) . lc($2)}ge;
615 s/\s*$/:/ unless (/:\s*$/);
617 $$self{PENDING
}[-1][1] = $_;
619 if ($$self{USAGE_SKIPPING
}) {
620 pop @
{ $$self{PENDING
} };
622 $self->SUPER::_handle_element_end
($element);
628 $self->SUPER::start_document
();
629 my $msg = $self->{USAGE_OPTIONS
}->{-message
} or return 1;
630 my $out_fh = $self->output_fh();
631 print $out_fh "$msg\n";
636 $self->SUPER::begin_pod
(); ## Have to call superclass
637 my $msg = $self->{USAGE_OPTIONS
}->{-message
} or return 1;
638 my $out_fh = $self->output_handle();
639 print $out_fh "$msg\n";
642 sub preprocess_paragraph
{
646 ## See if this is a heading and we arent printing the entire manpage.
647 if (($self->{USAGE_OPTIONS
}->{-verbose
} < 2) && /^=head/) {
648 ## Change the title of the SYNOPSIS section to USAGE
649 s/^=head1\s+SYNOPSIS\s*$/=head1 USAGE/;
650 ## Try to do some lowercasing instead of all-caps in headings
651 s{([A-Z])([A-Z]+)}{((length($2) > 2) ? $1 : lc($1)) . lc($2)}ge;
652 ## Use a colon to end all headings
653 s/\s*$/:/ unless (/:\s*$/);
656 return $self->SUPER::preprocess_paragraph
($_);
659 1; # keep require happy