How to create POD and use pod2usage in perl?

13,366

Solution 1

I do this using Getopt::Long together with Pod::Usage. (I got into this habit after reading a tutorial on the PerlMonks site, so here's the link to that as well.) It looks something like this example:

use Getopt::Long;
use Pod::Usage;

my( $opt_help, $opt_man, $opt_full, $opt_admins, $opt_choose, $opt_createdb, );

GetOptions(
    'help!'                 =>      \$opt_help,
    'man!'                  =>      \$opt_man,
    'full!'                 =>      \$opt_full,
    'admin|admins!'         =>      \$opt_admins,
    'choose|select|c=s'     =>      \$opt_choose,
    'createdb!'             =>      \$opt_createdb,
)
  or pod2usage( "Try '$0 --help' for more information." );

pod2usage( -verbose => 1 ) if $opt_help;
pod2usage( -verbose => 2 ) if $opt_man;

The options other than $opt_man and $opt_help are irrelevant to you in that example. I just copied the top of a random script I had here.

After that, you just need to write the POD. Here's a good link describing the basics of POD itself.

Edit: In response to the OP's question in the comments, here's how you might print just the NAME section when passed an appropriate option. First, add another option to the hash of options in GetOptions. Let's use 'name' => \$opt_name here. Then add this:

pod2usage(-verbose => 99, -sections => "NAME") if $opt_name;

Verbose level 99 is magic: it allows you to choose one or more sections only to be printed. See the documentation of Pod::Usage under -sections for more details. Note that -sections (the name) is plural even if you only want one section.

Solution 2

There are lots of good examples in the perlpod manpage. Pod2usage is explained here.

Share:
13,366
Anandan
Author by

Anandan

Updated on June 04, 2022

Comments

  • Anandan
    Anandan about 2 years

    I want to create a POD for my own custom command and display the syntax for that using pod2usage() function..

    Can anyone give me a simple example for it?

    Regards, Anandan

  • Brian Agnew
    Brian Agnew almost 15 years
    I don't see pod2usage mentioned there, though ?
  • ire_and_curses
    ire_and_curses almost 15 years
    @Brian Agnew: Yes, you're right. I've edited my answer to link to pod2usage explanation and examples.
  • Anandan
    Anandan almost 15 years
    thanks for the reply..that was useful.. but i have one more query here. i want to print only the "NAME" section using this.. i dunno how to do that.can you help m with that??
  • Anandan
    Anandan almost 15 years
    pod2usage(-section=>'NAME'); prints the NAME + other sections. this doesnt help me
  • Telemachus
    Telemachus almost 15 years
    @Anandan: I added an explanation about how to do this in the answer itself.