xref: /openbsd-src/gnu/usr.bin/perl/cpan/Pod-Usage/lib/Pod/Usage.pm (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1#############################################################################
2# Pod/Usage.pm -- print usage messages for the running script.
3#
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
7# as Perl itself.
8#############################################################################
9
10package Pod::Usage;
11use strict;
12
13use vars qw($VERSION @ISA @EXPORT);
14$VERSION = '1.61';  ## Current version of this package
15require  5.005;    ## requires this Perl version or later
16
17#use diagnostics;
18use Carp;
19use Config;
20use Exporter;
21use File::Spec;
22
23@EXPORT = qw(&pod2usage);
24BEGIN {
25    $Pod::Usage::Formatter ||=
26      ( $] >= 5.005_58 ? 'Pod::Text' : 'Pod::PlainText');
27    eval "require $Pod::Usage::Formatter";
28    die $@ if $@;
29    @ISA = ( $Pod::Usage::Formatter );
30}
31
32require Pod::Select;
33
34##---------------------------------------------------------------------------
35
36##---------------------------------
37## Function definitions begin here
38##---------------------------------
39
40sub pod2usage {
41    local($_) = shift;
42    my %opts;
43    ## Collect arguments
44    if (@_ > 0) {
45        ## Too many arguments - assume that this is a hash and
46        ## the user forgot to pass a reference to it.
47        %opts = ($_, @_);
48    }
49    elsif (!defined $_) {
50      $_ = '';
51    }
52    elsif (ref $_) {
53        ## User passed a ref to a hash
54        %opts = %{$_}  if (ref($_) eq 'HASH');
55    }
56    elsif (/^[-+]?\d+$/) {
57        ## User passed in the exit value to use
58        $opts{'-exitval'} =  $_;
59    }
60    else {
61        ## User passed in a message to print before issuing usage.
62        $_  and  $opts{'-message'} = $_;
63    }
64
65    ## Need this for backward compatibility since we formerly used
66    ## options that were all uppercase words rather than ones that
67    ## looked like Unix command-line options.
68    ## to be uppercase keywords)
69    %opts = map {
70        my ($key, $val) = ($_, $opts{$_});
71        $key =~ s/^(?=\w)/-/;
72        $key =~ /^-msg/i   and  $key = '-message';
73        $key =~ /^-exit/i  and  $key = '-exitval';
74        lc($key) => $val;
75    } (keys %opts);
76
77    ## Now determine default -exitval and -verbose values to use
78    if ((! defined $opts{'-exitval'}) && (! defined $opts{'-verbose'})) {
79        $opts{'-exitval'} = 2;
80        $opts{'-verbose'} = 0;
81    }
82    elsif (! defined $opts{'-exitval'}) {
83        $opts{'-exitval'} = ($opts{'-verbose'} > 0) ? 1 : 2;
84    }
85    elsif (! defined $opts{'-verbose'}) {
86        $opts{'-verbose'} = (lc($opts{'-exitval'}) eq 'noexit' ||
87                             $opts{'-exitval'} < 2);
88    }
89
90    ## Default the output file
91    $opts{'-output'} = (lc($opts{'-exitval'}) eq 'noexit' ||
92                        $opts{'-exitval'} < 2) ? \*STDOUT : \*STDERR
93            unless (defined $opts{'-output'});
94    ## Default the input file
95    $opts{'-input'} = $0  unless (defined $opts{'-input'});
96
97    ## Look up input file in path if it doesnt exist.
98    unless ((ref $opts{'-input'}) || (-e $opts{'-input'})) {
99        my $basename = $opts{'-input'};
100        my $pathsep = ($^O =~ /^(?:dos|os2|MSWin32)$/i) ? ';'
101                            : (($^O eq 'MacOS' || $^O eq 'VMS') ? ',' :  ':');
102        my $pathspec = $opts{'-pathlist'} || $ENV{PATH} || $ENV{PERL5LIB};
103
104        my @paths = (ref $pathspec) ? @$pathspec : split($pathsep, $pathspec);
105        for my $dirname (@paths) {
106            $_ = File::Spec->catfile($dirname, $basename)  if length;
107            last if (-e $_) && ($opts{'-input'} = $_);
108        }
109    }
110
111    ## Now create a pod reader and constrain it to the desired sections.
112    my $parser = new Pod::Usage(USAGE_OPTIONS => \%opts);
113    if ($opts{'-verbose'} == 0) {
114        $parser->select('(?:SYNOPSIS|USAGE)\s*');
115    }
116    elsif ($opts{'-verbose'} == 1) {
117        my $opt_re = '(?i)' .
118                     '(?:OPTIONS|ARGUMENTS)' .
119                     '(?:\s*(?:AND|\/)\s*(?:OPTIONS|ARGUMENTS))?';
120        $parser->select( '(?:SYNOPSIS|USAGE)\s*', $opt_re, "DESCRIPTION/$opt_re" );
121    }
122    elsif ($opts{'-verbose'} >= 2 && $opts{'-verbose'} != 99) {
123        $parser->select('.*');
124    }
125    elsif ($opts{'-verbose'} == 99) {
126        my $sections = $opts{'-sections'};
127        $parser->select( (ref $sections) ? @$sections : $sections );
128        $opts{'-verbose'} = 1;
129    }
130
131    ## Check for perldoc
132    my $progpath = File::Spec->catfile($Config{scriptdirexp}
133	|| $Config{scriptdir}, 'perldoc');
134
135    my $version = sprintf("%vd",$^V);
136    if ($Config{versiononly} and $Config{startperl} =~ /\Q$version\E$/ ) {
137      $progpath .= $version;
138    }
139    $opts{'-noperldoc'} = 1 unless -e $progpath;
140
141    ## Now translate the pod document and then exit with the desired status
142    if (      !$opts{'-noperldoc'}
143         and  $opts{'-verbose'} >= 2
144         and  !ref($opts{'-input'})
145         and  $opts{'-output'} == \*STDOUT )
146    {
147       ## spit out the entire PODs. Might as well invoke perldoc
148       print { $opts{'-output'} } ($opts{'-message'}, "\n") if($opts{'-message'});
149       if(defined $opts{-input} && $opts{-input} =~ /^\s*(\S.*?)\s*$/) {
150         # the perldocs back to 5.005 should all have -F
151	 # without -F there are warnings in -T scripts
152         system($progpath, '-F', $1);
153         if($?) {
154           # RT16091: fall back to more if perldoc failed
155           system(($Config{pager} || $ENV{PAGER} || '/bin/more'), $1);
156         }
157       } else {
158         croak "Unspecified input file or insecure argument.\n";
159       }
160    }
161    else {
162       $parser->parse_from_file($opts{'-input'}, $opts{'-output'});
163    }
164
165    exit($opts{'-exitval'})  unless (lc($opts{'-exitval'}) eq 'noexit');
166}
167
168##---------------------------------------------------------------------------
169
170##-------------------------------
171## Method definitions begin here
172##-------------------------------
173
174sub new {
175    my $this = shift;
176    my $class = ref($this) || $this;
177    my %params = @_;
178    my $self = {%params};
179    bless $self, $class;
180    if ($self->can('initialize')) {
181        $self->initialize();
182    } else {
183        # pass through options to Pod::Text
184        my %opts;
185       	for (qw(alt code indent loose margin quotes sentence stderr utf8 width)) {
186            my $val = $params{USAGE_OPTIONS}{"-$_"};
187            $opts{$_} = $val if defined $val;
188        }
189        $self = $self->SUPER::new(%opts);
190        %$self = (%$self, %params);
191    }
192    return $self;
193}
194
195sub select {
196    my ($self, @sections) = @_;
197    if ($ISA[0]->can('select')) {
198        $self->SUPER::select(@sections);
199    } else {
200        # we're using Pod::Simple - need to mimic the behavior of Pod::Select
201        my $add = ($sections[0] eq '+') ? shift(@sections) : '';
202        ## Reset the set of sections to use
203        unless (@sections) {
204          delete $self->{USAGE_SELECT} unless ($add);
205          return;
206        }
207        $self->{USAGE_SELECT} = []
208          unless ($add && $self->{USAGE_SELECT});
209        my $sref = $self->{USAGE_SELECT};
210        ## Compile each spec
211        for my $spec (@sections) {
212          my $cs = Pod::Select::_compile_section_spec($spec);
213          if ( defined $cs ) {
214            ## Store them in our sections array
215            push(@$sref, $cs);
216          } else {
217            carp qq{Ignoring section spec "$spec"!\n};
218          }
219        }
220    }
221}
222
223# Override Pod::Text->seq_i to return just "arg", not "*arg*".
224sub seq_i { return $_[1] }
225
226# This overrides the Pod::Text method to do something very akin to what
227# Pod::Select did as well as the work done below by preprocess_paragraph.
228# Note that the below is very, very specific to Pod::Text.
229sub _handle_element_end {
230    my ($self, $element) = @_;
231    if ($element eq 'head1') {
232        $self->{USAGE_HEADINGS} = [ $$self{PENDING}[-1][1] ];
233        if ($self->{USAGE_OPTIONS}->{-verbose} < 2) {
234            $$self{PENDING}[-1][1] =~ s/^\s*SYNOPSIS\s*$/USAGE/;
235        }
236    } elsif ($element =~ /^head(\d+)$/ && $1) { # avoid 0
237        my $idx = $1 - 1;
238        $self->{USAGE_HEADINGS} = [] unless($self->{USAGE_HEADINGS});
239        $self->{USAGE_HEADINGS}->[$idx] = $$self{PENDING}[-1][1];
240    }
241    if ($element =~ /^head\d+$/) {
242        $$self{USAGE_SKIPPING} = 1;
243        if (!$$self{USAGE_SELECT} || !@{ $$self{USAGE_SELECT} }) {
244            $$self{USAGE_SKIPPING} = 0;
245        } else {
246            my @headings = @{$$self{USAGE_HEADINGS}};
247            for my $section_spec ( @{$$self{USAGE_SELECT}} ) {
248                my $match = 1;
249                for (my $i = 0; $i < $Pod::Select::MAX_HEADING_LEVEL; ++$i) {
250                    $headings[$i] = '' unless defined $headings[$i];
251                    my $regex   = $section_spec->[$i];
252                    my $negated = ($regex =~ s/^\!//);
253                    $match  &= ($negated ? ($headings[$i] !~ /${regex}/)
254                                         : ($headings[$i] =~ /${regex}/));
255                    last unless ($match);
256                } # end heading levels
257                if ($match) {
258                  $$self{USAGE_SKIPPING} = 0;
259                  last;
260                }
261            } # end sections
262        }
263
264        # Try to do some lowercasing instead of all-caps in headings, and use
265        # a colon to end all headings.
266        if($self->{USAGE_OPTIONS}->{-verbose} < 2) {
267            local $_ = $$self{PENDING}[-1][1];
268            s{([A-Z])([A-Z]+)}{((length($2) > 2) ? $1 : lc($1)) . lc($2)}ge;
269            s/\s*$/:/  unless (/:\s*$/);
270            $_ .= "\n";
271            $$self{PENDING}[-1][1] = $_;
272        }
273    }
274    if ($$self{USAGE_SKIPPING} && $element !~ m/^over-/) {
275        pop @{ $$self{PENDING} };
276    } else {
277        $self->SUPER::_handle_element_end($element);
278    }
279}
280
281# required for Pod::Simple API
282sub start_document {
283    my $self = shift;
284    $self->SUPER::start_document();
285    my $msg = $self->{USAGE_OPTIONS}->{-message}  or  return 1;
286    my $out_fh = $self->output_fh();
287    print $out_fh "$msg\n";
288}
289
290# required for old Pod::Parser API
291sub begin_pod {
292    my $self = shift;
293    $self->SUPER::begin_pod();  ## Have to call superclass
294    my $msg = $self->{USAGE_OPTIONS}->{-message}  or  return 1;
295    my $out_fh = $self->output_handle();
296    print $out_fh "$msg\n";
297}
298
299sub preprocess_paragraph {
300    my $self = shift;
301    local $_ = shift;
302    my $line = shift;
303    ## See if this is a heading and we arent printing the entire manpage.
304    if (($self->{USAGE_OPTIONS}->{-verbose} < 2) && /^=head/) {
305        ## Change the title of the SYNOPSIS section to USAGE
306        s/^=head1\s+SYNOPSIS\s*$/=head1 USAGE/;
307        ## Try to do some lowercasing instead of all-caps in headings
308        s{([A-Z])([A-Z]+)}{((length($2) > 2) ? $1 : lc($1)) . lc($2)}ge;
309        ## Use a colon to end all headings
310        s/\s*$/:/  unless (/:\s*$/);
311        $_ .= "\n";
312    }
313    return  $self->SUPER::preprocess_paragraph($_);
314}
315
3161; # keep require happy
317
318__END__
319
320=head1 NAME
321
322Pod::Usage, pod2usage() - print a usage message from embedded pod documentation
323
324=head1 SYNOPSIS
325
326  use Pod::Usage
327
328  my $message_text  = "This text precedes the usage message.";
329  my $exit_status   = 2;          ## The exit status to use
330  my $verbose_level = 0;          ## The verbose level to use
331  my $filehandle    = \*STDERR;   ## The filehandle to write to
332
333  pod2usage($message_text);
334
335  pod2usage($exit_status);
336
337  pod2usage( { -message => $message_text ,
338               -exitval => $exit_status  ,
339               -verbose => $verbose_level,
340               -output  => $filehandle } );
341
342  pod2usage(   -msg     => $message_text ,
343               -exitval => $exit_status  ,
344               -verbose => $verbose_level,
345               -output  => $filehandle   );
346
347  pod2usage(   -verbose => 2,
348               -noperldoc => 1  )
349
350=head1 ARGUMENTS
351
352B<pod2usage> should be given either a single argument, or a list of
353arguments corresponding to an associative array (a "hash"). When a single
354argument is given, it should correspond to exactly one of the following:
355
356=over 4
357
358=item *
359
360A string containing the text of a message to print I<before> printing
361the usage message
362
363=item *
364
365A numeric value corresponding to the desired exit status
366
367=item *
368
369A reference to a hash
370
371=back
372
373If more than one argument is given then the entire argument list is
374assumed to be a hash.  If a hash is supplied (either as a reference or
375as a list) it should contain one or more elements with the following
376keys:
377
378=over 4
379
380=item C<-message>
381
382=item C<-msg>
383
384The text of a message to print immediately prior to printing the
385program's usage message.
386
387=item C<-exitval>
388
389The desired exit status to pass to the B<exit()> function.
390This should be an integer, or else the string "NOEXIT" to
391indicate that control should simply be returned without
392terminating the invoking process.
393
394=item C<-verbose>
395
396The desired level of "verboseness" to use when printing the usage
397message. If the corresponding value is 0, then only the "SYNOPSIS"
398section of the pod documentation is printed. If the corresponding value
399is 1, then the "SYNOPSIS" section, along with any section entitled
400"OPTIONS", "ARGUMENTS", or "OPTIONS AND ARGUMENTS" is printed.  If the
401corresponding value is 2 or more then the entire manpage is printed.
402
403The special verbosity level 99 requires to also specify the -sections
404parameter; then these sections are extracted (see L<Pod::Select>)
405and printed.
406
407=item C<-sections>
408
409A string representing a selection list for sections to be printed
410when -verbose is set to 99, e.g. C<"NAME|SYNOPSIS|DESCRIPTION|VERSION">.
411
412Alternatively, an array reference of section specifications can be used:
413
414  pod2usage(-verbose => 99,
415            -sections => [ qw(fred fred/subsection) ] );
416
417=item C<-output>
418
419A reference to a filehandle, or the pathname of a file to which the
420usage message should be written. The default is C<\*STDERR> unless the
421exit value is less than 2 (in which case the default is C<\*STDOUT>).
422
423=item C<-input>
424
425A reference to a filehandle, or the pathname of a file from which the
426invoking script's pod documentation should be read.  It defaults to the
427file indicated by C<$0> (C<$PROGRAM_NAME> for users of F<English.pm>).
428
429If you are calling B<pod2usage()> from a module and want to display
430that module's POD, you can use this:
431
432  use Pod::Find qw(pod_where);
433  pod2usage( -input => pod_where({-inc => 1}, __PACKAGE__) );
434
435=item C<-pathlist>
436
437A list of directory paths. If the input file does not exist, then it
438will be searched for in the given directory list (in the order the
439directories appear in the list). It defaults to the list of directories
440implied by C<$ENV{PATH}>. The list may be specified either by a reference
441to an array, or by a string of directory paths which use the same path
442separator as C<$ENV{PATH}> on your system (e.g., C<:> for Unix, C<;> for
443MSWin32 and DOS).
444
445=item C<-noperldoc>
446
447By default, Pod::Usage will call L<perldoc> when -verbose >= 2 is
448specified. This does not work well e.g. if the script was packed
449with L<PAR>. The -noperldoc option suppresses the external call to
450L<perldoc> and uses the simple text formatter (L<Pod::Text>) to
451output the POD.
452
453=back
454
455=head2 Formatting base class
456
457The default text formatter depends on the Perl version (L<Pod::Text> or
458L<Pod::PlainText> for Perl versions E<lt> 5.005_58). The base class for
459Pod::Usage can be defined by pre-setting C<$Pod::Usage::Formatter> I<before>
460loading Pod::Usage, e.g.:
461
462    BEGIN { $Pod::Usage::Formatter = 'Pod::Text::Termcap'; }
463    use Pod::Usage qw(pod2usage);
464
465=head2 Pass-through options
466
467The following options are passed through to the underlying text formatter.
468See the manual pages of these modules for more information.
469
470  alt code indent loose margin quotes sentence stderr utf8 width
471
472=head1 DESCRIPTION
473
474B<pod2usage> will print a usage message for the invoking script (using
475its embedded pod documentation) and then exit the script with the
476desired exit status. The usage message printed may have any one of three
477levels of "verboseness": If the verbose level is 0, then only a synopsis
478is printed. If the verbose level is 1, then the synopsis is printed
479along with a description (if present) of the command line options and
480arguments. If the verbose level is 2, then the entire manual page is
481printed.
482
483Unless they are explicitly specified, the default values for the exit
484status, verbose level, and output stream to use are determined as
485follows:
486
487=over 4
488
489=item *
490
491If neither the exit status nor the verbose level is specified, then the
492default is to use an exit status of 2 with a verbose level of 0.
493
494=item *
495
496If an exit status I<is> specified but the verbose level is I<not>, then the
497verbose level will default to 1 if the exit status is less than 2 and
498will default to 0 otherwise.
499
500=item *
501
502If an exit status is I<not> specified but verbose level I<is> given, then
503the exit status will default to 2 if the verbose level is 0 and will
504default to 1 otherwise.
505
506=item *
507
508If the exit status used is less than 2, then output is printed on
509C<STDOUT>.  Otherwise output is printed on C<STDERR>.
510
511=back
512
513Although the above may seem a bit confusing at first, it generally does
514"the right thing" in most situations.  This determination of the default
515values to use is based upon the following typical Unix conventions:
516
517=over 4
518
519=item *
520
521An exit status of 0 implies "success". For example, B<diff(1)> exits
522with a status of 0 if the two files have the same contents.
523
524=item *
525
526An exit status of 1 implies possibly abnormal, but non-defective, program
527termination.  For example, B<grep(1)> exits with a status of 1 if
528it did I<not> find a matching line for the given regular expression.
529
530=item *
531
532An exit status of 2 or more implies a fatal error. For example, B<ls(1)>
533exits with a status of 2 if you specify an illegal (unknown) option on
534the command line.
535
536=item *
537
538Usage messages issued as a result of bad command-line syntax should go
539to C<STDERR>.  However, usage messages issued due to an explicit request
540to print usage (like specifying B<-help> on the command line) should go
541to C<STDOUT>, just in case the user wants to pipe the output to a pager
542(such as B<more(1)>).
543
544=item *
545
546If program usage has been explicitly requested by the user, it is often
547desirable to exit with a status of 1 (as opposed to 0) after issuing
548the user-requested usage message.  It is also desirable to give a
549more verbose description of program usage in this case.
550
551=back
552
553B<pod2usage> doesn't force the above conventions upon you, but it will
554use them by default if you don't expressly tell it to do otherwise.  The
555ability of B<pod2usage()> to accept a single number or a string makes it
556convenient to use as an innocent looking error message handling function:
557
558    use Pod::Usage;
559    use Getopt::Long;
560
561    ## Parse options
562    GetOptions("help", "man", "flag1")  ||  pod2usage(2);
563    pod2usage(1)  if ($opt_help);
564    pod2usage(-verbose => 2)  if ($opt_man);
565
566    ## Check for too many filenames
567    pod2usage("$0: Too many files given.\n")  if (@ARGV > 1);
568
569Some user's however may feel that the above "economy of expression" is
570not particularly readable nor consistent and may instead choose to do
571something more like the following:
572
573    use Pod::Usage;
574    use Getopt::Long;
575
576    ## Parse options
577    GetOptions("help", "man", "flag1")  ||  pod2usage(-verbose => 0);
578    pod2usage(-verbose => 1)  if ($opt_help);
579    pod2usage(-verbose => 2)  if ($opt_man);
580
581    ## Check for too many filenames
582    pod2usage(-verbose => 2, -message => "$0: Too many files given.\n")
583        if (@ARGV > 1);
584
585As with all things in Perl, I<there's more than one way to do it>, and
586B<pod2usage()> adheres to this philosophy.  If you are interested in
587seeing a number of different ways to invoke B<pod2usage> (although by no
588means exhaustive), please refer to L<"EXAMPLES">.
589
590=head1 EXAMPLES
591
592Each of the following invocations of C<pod2usage()> will print just the
593"SYNOPSIS" section to C<STDERR> and will exit with a status of 2:
594
595    pod2usage();
596
597    pod2usage(2);
598
599    pod2usage(-verbose => 0);
600
601    pod2usage(-exitval => 2);
602
603    pod2usage({-exitval => 2, -output => \*STDERR});
604
605    pod2usage({-verbose => 0, -output  => \*STDERR});
606
607    pod2usage(-exitval => 2, -verbose => 0);
608
609    pod2usage(-exitval => 2, -verbose => 0, -output => \*STDERR);
610
611Each of the following invocations of C<pod2usage()> will print a message
612of "Syntax error." (followed by a newline) to C<STDERR>, immediately
613followed by just the "SYNOPSIS" section (also printed to C<STDERR>) and
614will exit with a status of 2:
615
616    pod2usage("Syntax error.");
617
618    pod2usage(-message => "Syntax error.", -verbose => 0);
619
620    pod2usage(-msg  => "Syntax error.", -exitval => 2);
621
622    pod2usage({-msg => "Syntax error.", -exitval => 2, -output => \*STDERR});
623
624    pod2usage({-msg => "Syntax error.", -verbose => 0, -output => \*STDERR});
625
626    pod2usage(-msg  => "Syntax error.", -exitval => 2, -verbose => 0);
627
628    pod2usage(-message => "Syntax error.",
629              -exitval => 2,
630              -verbose => 0,
631              -output  => \*STDERR);
632
633Each of the following invocations of C<pod2usage()> will print the
634"SYNOPSIS" section and any "OPTIONS" and/or "ARGUMENTS" sections to
635C<STDOUT> and will exit with a status of 1:
636
637    pod2usage(1);
638
639    pod2usage(-verbose => 1);
640
641    pod2usage(-exitval => 1);
642
643    pod2usage({-exitval => 1, -output => \*STDOUT});
644
645    pod2usage({-verbose => 1, -output => \*STDOUT});
646
647    pod2usage(-exitval => 1, -verbose => 1);
648
649    pod2usage(-exitval => 1, -verbose => 1, -output => \*STDOUT});
650
651Each of the following invocations of C<pod2usage()> will print the
652entire manual page to C<STDOUT> and will exit with a status of 1:
653
654    pod2usage(-verbose  => 2);
655
656    pod2usage({-verbose => 2, -output => \*STDOUT});
657
658    pod2usage(-exitval  => 1, -verbose => 2);
659
660    pod2usage({-exitval => 1, -verbose => 2, -output => \*STDOUT});
661
662=head2 Recommended Use
663
664Most scripts should print some type of usage message to C<STDERR> when a
665command line syntax error is detected. They should also provide an
666option (usually C<-H> or C<-help>) to print a (possibly more verbose)
667usage message to C<STDOUT>. Some scripts may even wish to go so far as to
668provide a means of printing their complete documentation to C<STDOUT>
669(perhaps by allowing a C<-man> option). The following complete example
670uses B<Pod::Usage> in combination with B<Getopt::Long> to do all of these
671things:
672
673    use Getopt::Long;
674    use Pod::Usage;
675
676    my $man = 0;
677    my $help = 0;
678    ## Parse options and print usage if there is a syntax error,
679    ## or if usage was explicitly requested.
680    GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
681    pod2usage(1) if $help;
682    pod2usage(-verbose => 2) if $man;
683
684    ## If no arguments were given, then allow STDIN to be used only
685    ## if it's not connected to a terminal (otherwise print usage)
686    pod2usage("$0: No files given.")  if ((@ARGV == 0) && (-t STDIN));
687    __END__
688
689    =head1 NAME
690
691    sample - Using GetOpt::Long and Pod::Usage
692
693    =head1 SYNOPSIS
694
695    sample [options] [file ...]
696
697     Options:
698       -help            brief help message
699       -man             full documentation
700
701    =head1 OPTIONS
702
703    =over 8
704
705    =item B<-help>
706
707    Print a brief help message and exits.
708
709    =item B<-man>
710
711    Prints the manual page and exits.
712
713    =back
714
715    =head1 DESCRIPTION
716
717    B<This program> will read the given input file(s) and do something
718    useful with the contents thereof.
719
720    =cut
721
722=head1 CAVEATS
723
724By default, B<pod2usage()> will use C<$0> as the path to the pod input
725file.  Unfortunately, not all systems on which Perl runs will set C<$0>
726properly (although if C<$0> isn't found, B<pod2usage()> will search
727C<$ENV{PATH}> or else the list specified by the C<-pathlist> option).
728If this is the case for your system, you may need to explicitly specify
729the path to the pod docs for the invoking script using something
730similar to the following:
731
732    pod2usage(-exitval => 2, -input => "/path/to/your/pod/docs");
733
734In the pathological case that a script is called via a relative path
735I<and> the script itself changes the current working directory
736(see L<perlfunc/chdir>) I<before> calling pod2usage, Pod::Usage will
737fail even on robust platforms. Don't do that. Or use L<FindBin> to locate
738the script:
739
740    use FindBin;
741    pod2usage(-input => $FindBin::Bin . "/" . $FindBin::Script);
742
743=head1 AUTHOR
744
745Please report bugs using L<http://rt.cpan.org>.
746
747Marek Rouchal E<lt>marekr@cpan.orgE<gt>
748
749Brad Appleton E<lt>bradapp@enteract.comE<gt>
750
751Based on code for B<Pod::Text::pod2text()> written by
752Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>
753
754=head1 ACKNOWLEDGMENTS
755
756Steven McDougall E<lt>swmcd@world.std.comE<gt> for his help and patience
757with re-writing this manpage.
758
759=head1 SEE ALSO
760
761B<Pod::Usage> is now a standalone distribution.
762
763L<Pod::Parser>, L<Pod::Perldoc>, L<Getopt::Long>, L<Pod::Find>, L<FindBin>,
764L<Pod::Text>, L<Pod::PlainText>, L<Pod::Text::Termcap>
765
766=cut
767
768