Question

Is there a standard way of adding a help function to a script? The simplest way would maybe to take an argument and print some text if it's "-help" or something. Does anyone have any examples on how to do this?

Thanks!

No correct solution

OTHER TIPS

Consider Getopt::Long plus Pod::Usage. My usual pattern for writing CLI tools:

#!/usr/bin/env perl
# ABSTRACT: Short tool description
# PODNAME: toolname
use autodie;
use strict;
use utf8;
use warnings qw(all);

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

# VERSION

=head1 SYNOPSIS

    toolname [options] files

=head1 DESCRIPTION

...

=cut

GetOptions(
    q(help)             => \my $help,
    q(verbose)          => \my $verbose,
) or pod2usage(q(-verbose) => 1);
pod2usage(q(-verbose) => 1) if $help;

# Actual code below

easy to use this :

if( $ARGV[0] eq '-h' || $ARGV[0] eq '-help')
{
help();
exit;
}


sub help { print "My help blah blah blah\n";
}

Take a look at https://github.com/qazwart/SVN-Watcher-Hook/blob/master/svn-watch.pl. I use a technique to combine the Getopt::Long module and the Pod::Usage module.

The main action occurs in lines 97 through 106 and in lines 108 through 110.

The Getopt::Long is a very common module to use since it handles command line arguments with easy. Using Pod documentation is rarer. However, all CPAN modules and all Perl built in modules use Pod documentation, so if you don't know it, learn it. POD is not very difficult to learn, and it's built into Perl, so all Perl programs can be self-documenting. You can print out the POD documentation of any program by using the perldoc command. Try this:

$ perldoc File::Find

You can also use the pod2html, pod2text and other types of translation commands to print POD documentation into HTML, etc.

Before I knew about POD, I would put something like this at the top of my program:

########################################################
# USAGE
#
my $USAGE =<<USAGE;

     Usage:

         foo [ -baz -fu <bar>] [-help]

         where:

             baz: yadda, yadda, yadda
             fu:  yadda, yadda, yadda
           help:  Prints out this helpful message

USAGE
#
######################################################

Then, in my program, I could do this:

if ($help) {
    print "$USAGE\n";
    exit 0;
}

This way, someone could look at the code and read the usage text. This would also be the same text that would print out when you used the -help parameter.

The way I do this is to utilise Getopt::Std to find an -h flag from the command line arguments.

use strict;
use warnings;
use Getopt::Std;

my %args;
getopts('h', \%args);

my $help = "help goes here. You can use
more than one line to format the text";

die $help if $args{h};
# otherwise continue with script...

A more sophisticated approach is to use POD::usage, although I have not tried this way personally.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top