#1 Automatic Help Option

Writing a wicked cool Perl script is nice, but it's even better if you can get other people to use it. One of the things most users really want is a help function. Our first wicked cool Perl script is a module to implement a --help operation.

Most good Perl scripts use the Plain Old Documentation (POD) feature of Perl to describe themselves. This module intercepts the --help on the command line and then prints out the POD for the program being run.


Note:

The official versions of the scripts in this book do contain POD. However, the documentation has been removed for the versions printed here to save space and eliminate redundancy. The full versions of the scripts (with POD) can be downloaded from the website www.nostarch.com/wcps.htm.


The Code

  1 use strict;
  2 use warnings;
  3
  4 INIT {
  5    if (($#ARGV == 0) && ($ARGV[0] eq "--help")) {
  6        system("perldoc $0");
  7        exit (0);
  8    }
  9 }
 10
 11 1;

Using the Module

To use the module, simply put the following line in your code:

use help;

Here's a small test program:

  1 #!/usr/bin/perl
  2 use strict;
  3 use warnings;
  4 =pod
  5
  6 =head1 NAME
  7
  8 Help test.
  9
 10 =head1 DESCRIPTION
 11
 12 If you read this the test worked.
 13
 14 =cut
 15
 16 use help;
 17 print "You didn't put --help on the command line
";

The Results

HELP_TEST(1)  User Contributed Perl Documentation    HELP_TEST(1)

NAME
       Help test.

DESCRIPTION
       If you read this the test worked.

perl v5.8.               2004-10-10             HELP_TEST(1)

How It Works

Perl has a number of special control blocks. In this program, the INIT block is called before the main program starts. It looks on the command line, and if it sees --help, it prints the documentation. The printing is done using the perldoc command, which is part of the Perl distribution.

The command looks for the program specified on the command line (in this case, it's the name of the program, or $0) and prints the program's documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset