Adding a help command to a script

user1758367 picture user1758367 · Dec 10, 2012 · Viewed 11.3k times · Source

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!

Answer

creaktive picture creaktive · Dec 10, 2012

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