NAME

Getopt::Pad - Declarative command line parsing with types, subcommands and config files

SYNOPSIS

use v5.26;
use Getopt::Pad;

my $opt = GetOptions(
    description => 'Copy a directory to a backup location.',
    options     => {
        'target|t' => {
            type     => 'dir',
            required => 1,
            help     => 'Directory the backup is written to',
        },
        'keep' => {
            type    => 'int',
            default => 7,
            min     => 1,
            help    => 'Number of backups to keep',
        },
        'exclude|x' => {
            type     => 'string',
            multiple => 1,
            help     => 'Pattern of files to skip; repeat for more patterns',
        },
        'compress' => {
            type    => 'bool',
            default => 1,
            help    => 'Compress the backup; --no-compress turns it off',
        },
        'verbose|v' => {
            type => 'counter',
            help => 'Print more details; repeat for even more (-vv)',
        },
    },
    args => [
        { short => 'source', type => 'dir', required => 1, help => 'Directory to back up' },
    ],
);

# backup -t /mnt/backup -x '*.tmp' -x '*.log' -vv --no-compress photos
say $opt->source;                        # photos
say $opt->target;                        # /mnt/backup
say $opt->keep;                          # 7 (the default)
say join ', ', $opt->exclude->@*;        # *.tmp, *.log
say $opt->compress ? 'yes' : 'no';       # no
say $opt->verbose;                       # 2

DESCRIPTION

Getopt::Pad parses the command line of a Perl program. You describe the command line once, as a data structure called the spec: it names every option and positional argument, and can give each one a type, a default value, a list of allowed values and a help text. GetOptions reads @ARGV according to that spec, checks every value, and returns an object with one method per option and argument. --log-level debug becomes $opt->logLevel, which returns 'debug'.

From the same spec, Getopt::Pad also provides:

  • Typed values. Strings, integers, floats, file and directory paths, URLs, flags, negatable booleans and counters, with bounds, existence checks, lists of allowed values and custom checks. You can add your own types. See "TYPES".

  • Value shapes. An option can hold one value, a list of values (--tag a --tag b, or --tag a,b), a mapping (--define os=linux) or a list of records (--server 0.host=a --server 0.port=80). See "multiple", "csv", "hash" and "objectlist".

  • Subcommands. A command line like tool image resize --width 640 is described by nesting specs. Every command has its own options, arguments and help. See "COMMANDS".

  • Config files. Option values can also come from YAML or JSON files, for every command, with the precedence command line, then config file, then default. You can add other file formats. See "CONFIG FILES".

  • Generated help. --help prints a formatted usage text, wrapped to the terminal width and colored on a terminal. --version prints the program version. See "HELP OUTPUT".

  • Shell completion. --create-completions bash (or zsh) prints a completion script that completes commands, options, allowed values and paths. See "SHELL COMPLETION".

  • Clear errors. A wrong command line prints the specific problem and the help text, and exits with status 2. A mistake in the spec itself makes GetOptions die immediately with a message that points at your GetOptions call. See "ERRORS AND EXIT STATUS".

How this documentation is organized

Getopt::Pad::Tutorial

A step-by-step introduction. Start here if you have not used Getopt::Pad before.

Getopt::Pad::Cookbook

Short recipes for common tasks, such as "Repeating an option (multiple)" or "Options for all commands (inherit)". Each recipe shows the spec, a command line and the result.

Getopt::Pad (this page)

The complete reference: every spec key, every type, the command line syntax, config files, help output, completion and all error messages.

Getopt::Pad::Result

The object GetOptions returns.

Getopt::Pad::Type

How to write your own option types.

Getopt::Pad::Config::Format

How to support another config file format.

The distribution also contains runnable example scripts in its examples/ directory, see "EXAMPLES".

Sections of this page

"TERMINOLOGY" and "QUICK REFERENCE"

The terms used here, and one table per kind of key.

"FUNCTIONS", "SPEC KEYS", "OPTION SPECS", "ARG SPECS", "TYPES"

Everything you can write in a spec.

"COMMAND LINE SYNTAX", "COMMANDS", "VALUES AND PRECEDENCE"

How the command line is read, and where values come from.

"CONFIG FILES", "AUTOMATIC OPTIONS", "HELP OUTPUT", "SHELL COMPLETION"

What Getopt::Pad adds to a program by itself.

"RESULT OBJECT"

What GetOptions returns.

"ERRORS AND EXIT STATUS", "DIAGNOSTICS"

What happens when something is wrong, and every message.

"ENVIRONMENT", "EXTENDING", "EXAMPLES", "CAVEATS", "REQUIREMENTS"

Everything else.

TERMINOLOGY

Terms used throughout this documentation:

spec

The arguments you pass to GetOptions: a list of key/value pairs that describes the whole command line.

option

A named switch on the command line, such as --verbose or --log-level debug. Options are declared under the options key.

primary name, alias

An option is declared with one or more names separated by |, such as 'owner|o'. The first name (owner) is the primary name. It names the reader and is shown in the help output. The other names (o) are aliases: the command line accepts them and shell completion offers them, but readers and the help output use only the primary name.

arg

A positional argument: a word on the command line that is not an option, such as the file name in tool --verbose notes.txt. Args are declared in order under the args key. Error messages about args call them argument (missing required argument <source>). In the messages Option NAME requires an argument and Option NAME does not take an argument, which come from Getopt::Long, "argument" means the value of an option instead.

command, subcommand

A named mode of a program, selected by a word on the command line (the command name), such as resize in tool resize --width 640. Commands are also known as subcommands. Each command has a command spec under the commands key, and commands can be nested.

level

The top level of the spec, or one command. Every level has its own options and either args or commands. tool image resize involves three levels: the top level, the command image and the command image resize.

command path

The command words that lead to a level, separated by spaces, such as image resize. The top level has an empty command path. Help output and error messages identify commands by their command path.

option group

The heading an option is listed under in the help output, set with the group key. The same name is used as a section of config files. Options without a group are in the group Options.

reader

A method of the result object that returns the value of one option or arg (a getter), such as $opt->logLevel for the option log-level. See "Reader names".

result object

The object GetOptions returns. There is one result object per level that the command line selects; each one holds the result object of the next level as its subcommand. See "RESULT OBJECT".

value source

Where the value of an option comes from: the command line, a config file, or the default in the spec. See "VALUES AND PRECEDENCE".

automatic option

An option that Getopt::Pad adds by itself, such as --help. See "AUTOMATIC OPTIONS".

inherited option

An option that is declared on one level and also accepted on the command line of every level below it. See "inherit".

config block

The config key of the spec, which enables config files. See "CONFIG FILES".

user error, spec error

A user error is a mistake on the command line or in a config file. It is reported to the user, and the program exits with status 2. A spec error is a mistake in the spec, that is, in your program. It makes GetOptions die. See "ERRORS AND EXIT STATUS".

QUICK REFERENCE

Each key below links to its full description.

Spec keys

Key              Allowed on       Value
---------------  ---------------  ---------------------------------------
options          every level      hashref: option key => option spec
args             every level      arrayref of arg specs
commands         every level      hashref: command name => command spec
commandRequired  levels with      boolean, default true
                 commands
description      every level      string
examples         every level      arrayref of { text => ..., args => ... }
config           top level only   hashref, see the config block keys
version          top level only   string, default $main::VERSION
argv             top level only   arrayref of words, default @ARGV

See "options", "args", "commands", "commandRequired", "description", "examples", "config", "version" and "argv".

Option spec keys

Key                  Value                  Default    Notes
-------------------  ---------------------  ---------  ------------------------------
type                 type name              'flag'     see TYPES
required             boolean                false      not with default
default              value in the           none       not with required
                     option's shape
help                 string                 ''
group                string                 'Options'
hidden               boolean                false
valid                arrayref or coderef    none       allowed values
lazyValid            coderef                none       custom check
multiple             boolean                false      value-taking types only
csv                  boolean                false      requires multiple
hash                 boolean                false      value-taking types only
objectlist           boolean                false      value-taking types only
inherit              boolean                false      levels with commands only
typehint             string                 type's     label shown in the help
min, max             number                 none       int and float only
mustExist            boolean                false      file and dir only
createPathIfMissing  boolean                false      file and dir only

See "OPTION SPECS". multiple, hash and objectlist exclude each other. mustExist and createPathIfMissing exclude each other.

Arg spec keys

Key                  Value      Default    Notes
-------------------  ---------  ---------  -------------------------------
short                name       -          mandatory, names the reader
type                 type name  'string'   value-taking types only
required             boolean    false      required args come first
multiple             boolean    false      last arg only, takes the rest
help                 string     ''
typehint             string     type's     label shown in the help
min, max             number     none       int and float only
mustExist            boolean    false      file and dir only
createPathIfMissing  boolean    false      file and dir only

See "ARG SPECS".

Config block keys

Key          Value            Default  Notes
-----------  ---------------  -------  -----------------------------------
format       format name      -        mandatory: 'yaml', 'yml' or 'json'
paths        arrayref         []       files loaded automatically, in order
defaultPath  path             none     loaded by a bare --config
autoload     boolean          true     load 'paths' when --config is absent

See "CONFIG FILES".

Type names

Type names                   Command line         Reader value
---------------------------  -------------------  -------------------------
flag (default for options)   --name               1, or undef when absent
bool, boolean, !             --name, --no-name    1 or 0, undef when absent
counter, count, +            --name --name, -nn   times given, or undef
string, str, s (default      --name VALUE         the string
  for args)
int, integer, i              --name 42            number
float, num, number, f        --name 1.5           number
file                         --name PATH          the path
dir, directory               --name PATH          the path
url, uri                     --name URL           the URL

See "TYPES".

FUNCTIONS

GetOptions

my $opt = GetOptions(%spec);

GetOptions is exported by default. It takes the spec as a list of key/value pairs (see "SPEC KEYS"), parses the command line and returns the result object of the top level (see "RESULT OBJECT").

It returns only when the command line is valid. In every other case it ends the program itself:

  • On a user error, it prints the error message and the help text of the affected level to STDERR and exits with status 2.

  • When the command line contains an automatic option such as --help, --version, --create-completions or --create-default-config, it prints that option's output to STDOUT and exits with status 0.

  • When a generated shell completion script calls the program (see "SHELL COMPLETION"), it prints the completion candidates and exits with status 0.

Before it looks at the command line, GetOptions checks the whole spec. A mistake in the spec, such as an unknown key or an invalid default, makes it die with a spec error (see "ERRORS AND EXIT STATUS").

GetOptions reads @ARGV unless you pass the words to parse with the "argv" key. It never modifies @ARGV.

SPEC KEYS

A spec is a list of key/value pairs. The top level of a spec and the spec of every command (see "commands") accept the keys "options", "args", "commands", "commandRequired", "description" and "examples". The keys "config", "version" and "argv" are accepted on the top level only. Any other key is a spec error.

options

options => {
    'log-level' => { type => 'string', default => 'info' },
    'verbose|v' => { type => 'counter' },
},

A hashref that maps option keys to option specs. The key is the option's name, optionally followed by aliases separated by |. The value is a hashref describing the option, see "OPTION SPECS".

args

args => [
    { short => 'source', required => 1 },
    { short => 'target' },
],

An arrayref of arg specs, one per positional argument, in command line order. See "ARG SPECS". A level cannot have both args and commands.

commands

commands => {
    add    => { args => [{ short => 'name', required => 1 }] },
    remove => { args => [{ short => 'name', required => 1 }] },
},

A hashref that maps command names to the spec of that command. A command spec accepts the same keys as the top level, except config, version and argv, so commands can have commands of their own. A command name must start with a letter, followed by letters, digits, underscores or dashes. See "COMMANDS" for how commands are parsed and read.

commandRequired

commandRequired => 0,

On a level with commands, whether the command line must name one of them. The default is true: a missing command is a user error ("missing command"). With a false value, the command word may be left out; the level's command and subcommand methods then return undef, and there is no result object for a command. Using commandRequired on a level without commands is a spec error.

description

description => 'Copy a directory to a backup location.',

A one-line description of the program or command. It is shown in the second line of the help output. The description of a command is also shown next to the command's name in the Commands section of the parent level's help output.

examples

examples => [
    { text => 'Back up your photos', args => '--target /mnt/backup ~/photos' },
],

An arrayref of usage examples shown at the end of the help output. Each example is a hashref with the keys text (a short explanation) and args (the command line after the program name and command path, as a single string). Both keys are mandatory. The help output shows the example as:

# Examples:
## Back up your photos
##   backup --target /mnt/backup ~/photos

config

config => {
    format      => 'yaml',
    paths       => ['/etc/backup.yaml', '~/.backup.yaml'],
    defaultPath => '~/.backup.yaml',
},

Enables config files. The value is a hashref with the keys format (mandatory), paths, defaultPath and autoload. It also adds the automatic options --config and --create-default-config. See "CONFIG FILES". Top level only.

version

version => '1.2.0',

The version string that the automatic --version option prints, as PROGRAM VERSION (for example backup 1.2.0). Without this key, --version prints the value of $main::VERSION, that is, the our $VERSION of your script, or unknown when that is not set. Top level only.

argv

argv => ['--verbose', 'input.txt'],

An arrayref of words to parse instead of @ARGV. GetOptions copies the words; neither @ARGV nor this arrayref is modified. This is useful for tests (see "Testing a command line" in Getopt::Pad::Cookbook) and for parsing a command line that does not come from @ARGV. Top level only.

OPTION SPECS

Every entry under "options" has a key and a spec:

options => {
    'log-level|l' => {                 # key: primary name and aliases
        type    => 'string',           # spec: a hashref of the keys below
        default => 'info',
        valid   => ['debug', 'info', 'warn', 'error'],
        help    => 'How much to log',
    },
},

An option spec is a hashref. An empty hashref (verbose => {}) declares a plain flag. Any key not described in this section is a spec error, except the type-specific keys listed under "Type-specific keys".

Option names and aliases

The option key is the primary name, optionally followed by aliases, all separated by |: 'owner|o' declares the option --owner with the alias -o. Every name must start with a letter, followed by letters, digits, underscores or dashes.

A name of one letter is a short option: it is written with one dash (-o) and can be bundled with other short options (-vo dave). A longer name is written with two dashes (--owner). See "COMMAND LINE SYNTAX".

Names are case sensitive: -v and -V are different options. A name or alias may be used by only one option per level; an inherited option reserves its names on every level below (see "inherit").

Reader names

The reader of an option is named after its primary name, converted to camelCase: the name is split at dashes and underscores, and every part after the first starts with an upper case letter. The first part stays as it is.

Option or arg name   Reader
-------------------  ----------------
verbose              $opt->verbose
log-level            $opt->logLevel
dry_run              $opt->dryRun
work-dir-path        $opt->workDirPath
o                    $opt->o

Aliases have no readers. Two options or args of one level whose names map to the same reader (work-dir and work_dir) are a spec error. A name whose reader would be one of the methods every result object has is a spec error too, see "Reserved names".

type

type => 'int',

The type of the option's value, by name. The name is case insensitive. The default is flag: an option without a type takes no value. See "TYPES" for the built-in types and Getopt::Pad::Type for adding your own. An unknown type name is a spec error.

required

required => 1,

The option must be set, on the command line or in a config file. If neither sets it, parsing stops with the user error missing required option '--NAME'. This works for flags as well: a required flag must be given. A value from a config file satisfies required. The help output marks required options with [REQ]. required and "default" exclude each other.

default

default => 'info',              # a single value
default => ['a', 'b'],          # multiple
default => { os => 'linux' },   # hash
default => [{ host => 'a' }],   # objectlist

The value the reader returns when neither the command line nor a config file sets the option. The default must have the option's shape: a single value, an arrayref for a "multiple" option, a hashref for a "hash" option, or an arrayref of hashrefs for an "objectlist" option.

The default is checked like a value from the command line (type, "valid", "lazyValid", bounds) when GetOptions builds the spec. An invalid default is a spec error, even when the option is not used. The reader returns the checked value, for example a number for an int option. Every parse gets its own copy of a list or mapping default, so changing it does not affect later parses.

The help output shows the default in a Default line.

default => undef is allowed for single-value options and mostly means the same as no default. There are two differences: a custom type's prepare method is called with undef (see "prepare" in Getopt::Pad::Type), and --create-default-config writes the option into the file with an empty value (YAML ~, JSON null), which the program then rejects with no value given when it reads the file. Remove such lines from a generated file.

default and "required" exclude each other.

help

help => 'Number of backups to keep',

The help text shown next to the option in the help output. It is wrapped to the terminal width automatically. Without it, the option is listed with its name only.

group

group => 'Target',

The heading the option is listed under in the help output. Options without a group are listed under Options. The help output lists the groups in alphabetical order.

The group is also the section of a config file that sets the option (see "File layout"). On a level with commands, a spec with a "config" block cannot use the group name commands, because config files use that key for the command sections.

hidden

hidden => 1,

The option works as usual, but it is not listed in the help output and not offered by shell completion. Config files can still set it.

valid

valid => ['debug', 'info', 'warn', 'error'],        # a fixed list
valid => sub { [ map { $_->name } list_users() ] },   # computed when needed

The values the option accepts: a fixed set of choices, like an enum. Any other value is the user error 'VALUE' is not one of: ALLOWED, VALUES. The comparison is an exact string comparison (eq) with the value after the type's conversion, so for an int option --port 080 is compared as 80.

The value is either an arrayref of the allowed values, or a coderef that is called without arguments and returns such an arrayref. Use a coderef for lists that are only known at run time, such as ids from a database or file names in a directory. The coderef is called every time a value is checked (once per value for options with several values), when GetOptions checks the option's "default", and on every shell completion request for the option. It must return an arrayref; anything else is a spec error.

The help output lists the allowed values in a Valid line for an arrayref, but not for a coderef. Shell completion offers the allowed values in both cases. For options with several values ("multiple", "hash", "objectlist"), valid applies to every single value (for "hash" and "objectlist": to the values, not to the keys).

lazyValid

lazyValid => sub { my ($value) = @_; $value =~ /\A[a-z][a-z0-9-]*\z/ },

Your own validation code, for constraints that cannot be written as a list. Despite its name, lazyValid is not a list of allowed values computed later (a "valid" coderef does that); it is a yes/no check. The coderef is called with one value, after the type's conversion and after the "valid" check, and returns true to accept the value. A false result is the user error 'VALUE' is not a valid value. For options with several values, it is called once per value. lazyValid is not used for the help output or for shell completion.

If you want a more specific error message than "is not a valid value", write a custom type instead (see Getopt::Pad::Type), whose check method returns the message.

multiple

tag => { type => 'string', multiple => 1 },

The option may be given more than once. The reader returns an arrayref of all values in command line order:

$ tool --tag red --tag blue     # $opt->tag is ['red', 'blue']
$ tool                          # $opt->tag is []

When the option is not set anywhere and has no default, the reader returns an empty arrayref, so $opt->tag->@* is always safe. Every value is checked on its own. A config file sets the option with a list or a single value (see "Values in config files"). multiple needs a value-taking type (not flag, bool or counter) and excludes "hash" and "objectlist".

csv

tag => { type => 'string', multiple => 1, csv => 1 },

Accepts comma-separated lists: every value of a "multiple" option is split at commas, so a list can be given in one word. Whitespace around the items is removed, and one trailing comma is ignored. An empty item is the user error 'VALUE' contains an empty item.

$ tool --tag red,blue --tag green     # $opt->tag is ['red', 'blue', 'green']
$ tool --tag 'red, blue,'             # $opt->tag is ['red', 'blue']
$ tool --tag red,,blue                # error: contains an empty item

A single value in a config file is split the same way. A list in a config file is taken as it is, without splitting its items. There is no way to escape a comma. The help output shows the option as --tag <a,b,...>. csv without multiple is a spec error.

hash

define => { type => 'string', hash => 1 },

The option takes KEY=VALUE words and the reader returns a hashref:

$ tool --define os=linux --define arch=x86     # {os => 'linux', arch => 'x86'}
$ tool --define path=a=b                        # {path => 'a=b'}
$ tool                                          # {}

The word is split at the first =. Giving the same key again replaces its value. A word without = is a user error (Option define, key "os", requires a value), and so is an empty key. The values are checked with the type, "valid" and "lazyValid"; the keys are not checked. When the option is not set anywhere and has no default, the reader returns an empty hashref.

A default is a hashref, and a config file sets the option with a mapping. The value from the highest-priority value source replaces the others as a whole: --define os=bsd on the command line discards all keys from the config file (see "VALUES AND PRECEDENCE"). The help output shows the option as --define <key=value>. hash needs a value-taking type and excludes "multiple" and "objectlist".

objectlist

server => { type => 'string', objectlist => 1 },

The option takes INDEX.FIELD=VALUE words and the reader returns an arrayref of hashrefs, one per index, ordered by index:

$ tool --server 0.host=alpha --server 0.port=80 --server 1.host=beta
# $opt->server is [ { host => 'alpha', port => '80' }, { host => 'beta' } ]

INDEX is a number starting at 0. The indices used must be exactly 0 to n-1, in any order; a gap is the user error missing index N. FIELD consists of letters, digits, underscores and dashes. A word without = is the user error Option server, key "WORD", requires a value; a word whose key does not have the form INDEX.FIELD is the user error invalid key 'KEY', expected INDEX.FIELD=VALUE. Giving the same INDEX.FIELD again replaces its value. The values are checked with the type (so the port above stays a string for a string option), "valid" and "lazyValid". When the option is not set anywhere and has no default, the reader returns an empty arrayref.

A default is an arrayref of hashrefs, and a config file sets the option with a list of mappings. The help output shows the option as --server <N.key=value>. objectlist needs a value-taking type and excludes "multiple" and "hash".

inherit

GetOptions(
    options  => { 'verbose|v' => { type => 'counter', inherit => 1 } },
    commands => { scan => { ... }, report => { ... } },
);

Makes the option available on every level below the one that declares it, so it can be given before or after the command words:

$ tool -v scan        # both set $opt->verbose to 1
$ tool scan -v

The value still belongs to the declaring level: read it from that level's result object (here the top level's $opt->verbose, not $opt->subcommand->verbose), and set it in that level's groups of a config file.

If the option is given on several levels, the words are combined as if they had all been given on the declaring level: for a single value the last one wins, a "multiple" option collects all values, a "hash" option merges the pairs, and a counter adds up (tool -v scan -v gives 2).

The help output of every level below lists the option, and shell completion offers it there. No level below may declare an option or alias with one of its names. inherit is allowed only on levels that have commands; anywhere else it is a spec error.

typehint

typehint => 'Hostname',

Replaces the type label that the help output shows at the end of the help text. typehint => 'Hostname' renders as [Hostname]. Only the file, dir and url types have a label of their own ([File Path], [Path] and [URL]); for the other types, typehint adds a label where there was none. It must be a non-empty string.

Type-specific keys

Some types accept additional keys in the option or arg spec. Using them with another type is a spec error (unknown key(s)).

min, max

For int and float. The smallest and largest accepted value, inclusive. Values outside are user errors (5 is smaller than the minimum of 10). Both must be numbers and min must not be larger than max, or the spec is invalid.

mustExist

For file and dir. The path must exist when the command line is parsed: an existing file (not a directory) for file, an existing directory for dir. The help output marks the option with [has to exist].

Like every check, mustExist also applies to the "default", and defaults are checked when GetOptions builds the spec. A default path that does not exist on the machine the program runs on therefore makes GetOptions die with a spec error, even when the command line gives another path. Give a mustExist option a default only if the path is certain to exist.

createPathIfMissing

For file and dir. If the path does not exist, it is created: a directory with all missing parent directories for dir, an empty file and its missing parent directories for file. An existing path is left alone. The help output marks the option with [created if missing].

The path is created after all checks of that value passed, and only for the value that is finally used: a default is created only if neither the command line nor a config file overrides it. Nothing is created for --help and the other automatic options, or for a shell completion request. Values are processed one option at a time, so a path can already have been created when a later option or arg of the same command line turns out to be invalid. If the path cannot be created, that is a user error (cannot create directory 'PATH': REASON).

mustExist and createPathIfMissing exclude each other.

ARG SPECS

Args are the words of the command line that are not options. Every entry under "args" describes one of them, in order:

args => [
    { short => 'source', type => 'dir', required => 1, help => 'Directory to copy' },
    { short => 'target', type => 'dir', help => 'Where to copy to' },
],

An arg spec is a hashref with these keys:

short

Mandatory. The name of the arg. It names the reader (converted to camelCase like option names, see "Reader names") and is shown in the help output. Despite its name, it has nothing to do with short options: args have no names on the command line. It must start with a letter, followed by letters, digits, underscores or dashes.

type

The type of the value, by name (see "TYPES"). The default is string. Types that take no value (flag, bool, counter) are a spec error. The type-specific keys "min, max", "mustExist" and "createPathIfMissing" work as for options.

required

The arg must be given; a missing one is the user error missing required argument <NAME>. Required args must come before optional ones.

multiple

Only allowed on the last arg. It makes a multiple arg, which takes all remaining words; its reader returns an arrayref (an empty arrayref when there are none). With required, at least one word is needed. This is different from a "multiple" option, which is given several times.

help

The help text shown in the Arguments section of the help output.

typehint

Replaces the type label in the help output, see "typehint".

Args do not support default, valid, lazyValid, hidden, group, csv, hash, objectlist or inherit. An optional arg that is not given reads as undef. Words left over after the last arg are the user error unexpected extra argument 'WORD'. A level without args accepts no positional words at all.

Args are checked with their type, including mustExist, the bounds and createPathIfMissing. They cannot be set in config files.

TYPES

The type of an option or arg decides whether it takes a value, how the value is checked and converted, and what the reader returns. Most types have several names; they are interchangeable and case insensitive.

Types that take no value (flag, bool, counter) can be used for options only. All other types take a value and can be used for options and args.

flag

Names: flag. The default type of options.

A switch without a value: --dry-run. The reader returns 1 when the option is given and undef when it is not (unless there is a default). A flag cannot be turned off on the command line; use bool if you need that. In config files a flag accepts true, false, 1 and 0 (see "Values in config files"); false and 0 read as 0.

bool

Names: bool, boolean, !.

A switch that can be negated: --color sets it to 1, --no-color (or --nocolor) sets it to 0. The last one given wins. The reader returns undef when the option is not set anywhere and has no default. It is typically combined with default => 1 or default => 0. The help output shows the option as --[no-]color. In config files it accepts true, false, 1 and 0 (see "Values in config files").

counter

Names: counter, count, +.

A switch that counts how often it is given: -v -v -v, -vvv and --verbose -vv (with the alias v) all read as 3. The reader returns undef when the option is not set anywhere and has no default, so write $opt->verbose // 0 when you need a number. In config files it accepts non-negative integers.

string

Names: string, str, s. The default type of args.

Any value. The reader returns it unchanged.

int

Names: int, integer, i. Keys: "min, max".

An integer: optional + or -, followed by decimal digits (42, -7, +3, 007). The reader returns a number (007 reads as 7). Other values are the user error 'VALUE' is not an integer.

float

Names: float, num, number, f. Keys: "min, max".

A number in any notation Perl understands as a decimal number: 1.5, -2, .5, 1e3. Values spelled inf, infinity or nan are rejected with 'VALUE' is not a finite number. Hexadecimal values such as 0x10 are rejected with 'VALUE' is not a number. A value too large for a Perl number, such as 1e999, is accepted and reads as Inf; use max to exclude it. The reader returns a number. Other values are the user error 'VALUE' is not a number.

file

Names: file. Keys: "mustExist", "createPathIfMissing".

A path to a file. Without mustExist any value is accepted. The reader returns the path as given (a leading ~ is not expanded; the shell usually does that before the program sees the word). The help output labels the option [File Path]. Shell completion completes file names.

dir

Names: dir, directory. Keys: "mustExist", "createPathIfMissing".

A path to a directory. Otherwise the same as file. The help output labels the option [Path]. Shell completion completes directory names.

url

Names: url, uri.

A URL of the form scheme://rest: a scheme that starts with a letter (followed by letters, digits, +, . or -), then ://, then at least one character, without whitespace. https://example.com/x and file:///tmp/x are accepted; example.com and mailto:me@example.com are not. The help output labels the option [URL].

Custom types

You can add types, for example one that accepts only even numbers or one that converts 5m to 300 seconds. See Getopt::Pad::Type.

COMMAND LINE SYNTAX

Getopt::Pad accepts the following command line syntax (it uses Getopt::Long with the settings bundling, no_ignore_case and no_auto_abbrev). In this section, the value of an option is what the command line gives it, either as the next word or attached to the option.

Long options

Names longer than one letter are written with two dashes. A value follows as the next word or after =: --owner dave and --owner=dave are the same. Names must be written in full; abbreviations such as --own are unknown options. Case matters.

Short options

Single-letter names are written with one dash. A value follows as the next word or directly: -o dave and -odave are the same. Note that -o=dave sets the value =dave. The double-dash form --o is accepted as well.

Bundling

Several single-letter options can share one dash: -abc is -a -b -c, and -vvv counts three times. A letter that takes a value ends the bundle: -vxfoo is -v -x foo. Because of bundling, a long option written with one dash is read letter by letter: -force is read as -f -o -r -c -e, and every letter that is not a declared short option is reported as an unknown option.

Negation

A bool option is turned off with --no-NAME or --noNAME.

Repeating options

A single-value option given several times keeps the last value. A "multiple" option collects all values; a "hash" or "objectlist" option collects all pairs. A flag stays 1; a counter counts.

Values that start with a dash

A value-taking option always takes the next word as its value, even if it starts with a dash: --offset -5 and --pattern --x work. The only exception is --config, whose value is optional (see "Where config files are loaded from").

Order of options and args

On a level without commands, options and args can be mixed in any order: tool a.txt --verbose b.txt is the same as tool --verbose a.txt b.txt.

Options and commands

On a level with commands, the level's options must come before the command word. The first word that is not an option is the command name, and every word after it belongs to that command's level. An option of an outer level is an unknown option after the command word, unless it is inherited (see "inherit").

The end of options

The word -- ends option processing on its level: on a level without commands, every word after it is an arg, even if it starts with a dash. Use it for positional values that start with a dash, such as negative numbers: tool -- -5. Without --, -5 is read as the short option -5, which is unknown.

On a level with commands, the word after -- is the command name, and the command's level reads options again. So put -- after the command words: tool resize -- -5.

COMMANDS

Commands (subcommands) split a program into modes, each with its own options, args and help. They are declared under the "commands" key. The value for each command name is a spec with the same keys as the top level (except config, version and argv), so commands can be nested to any depth:

my $opt = GetOptions(
    options  => { 'dry-run' => { help => 'Show what would happen' } },
    commands => {
        image => {
            description => 'Work on images',
            commands    => {
                resize => {
                    description => 'Resize an image',
                    options     => { width => { type => 'int', min => 1 } },
                    args        => [{ short => 'file', type => 'file', required => 1 }],
                },
            },
        },
        document => {
            description => 'Work on documents',
            args        => [{ short => 'file', type => 'file', required => 1 }],
        },
    },
);

How commands are parsed

The command line is read level by level. On the top level, Getopt::Pad reads options until it reaches the first word that is not an option. That word must be the name of one of the level's commands, otherwise it is the user error unknown command 'WORD', expected one of: NAMES. The remaining words are read by that command's level in the same way, down to a level without commands, which reads its options and args.

For the command line

$ tool --dry-run image resize --width 640 cat.png
  • the top level reads --dry-run and the command name image,

  • the level image reads the command name resize,

  • the level image resize reads --width 640 and the arg cat.png.

A level with commands has no args. If the command line ends before a command is named, that is the user error missing command, expected one of: NAMES, unless the level sets "commandRequired" to a false value.

Reading the result

Each level that the command line selects produces its own result object. The top level's result object is returned by GetOptions. Its command method returns the name of the selected command, and its subcommand method returns that command's result object, which again has command and subcommand methods:

# tool --dry-run image resize --width 640 cat.png
$opt->dryRun;                                  # 1
$opt->command;                                 # 'image'
$opt->subcommand->command;                     # 'resize'
$opt->subcommand->subcommand->width;           # 640
$opt->subcommand->subcommand->file;            # 'cat.png'
$opt->subcommand->subcommand->command;         # undef (no commands)

Every result object has readers only for the options and args of its own level. See "Dispatching commands to subroutines" in Getopt::Pad::Cookbook for a way to run code per command.

Help for commands

--help prints the help of the level it is given on: tool --help shows the top level with the list of its commands, tool image resize --help shows the options and args of image resize. An error on the command line, or in the value of an option, is reported with the help of the level where it happened. An invalid value of an inherited option is reported with the help of the level that declares it, wherever on the command line it was given. An error in the structure of a config file (an unknown command or option, a parse error, a missing file) is reported with the help of the top level.

Options for all commands (global options)

An option that should work on every level, such as --verbose, is declared once on the top level with "inherit". Config files can set options of every level, see "File layout".

VALUES AND PRECEDENCE

Value sources

Every declared option gets its value from the first of these value sources that sets it:

  1. the command line;

  2. a config file (see "CONFIG FILES");

  3. the spec's "default".

The first source that sets the option provides the whole value; values from different sources are never merged. If the command line sets a "multiple" option, the list from the config file is ignored; if the command line sets a "hash" option, all keys from the config file are ignored. The same rule holds between config files, see "Where config files are loaded from".

If no source sets the option, a "required" option is a user error. Otherwise the reader returns:

  • an empty arrayref for "multiple" and "objectlist" options,

  • an empty hashref for "hash" options,

  • undef for all other options, including flags, bools and counters.

Args come from the command line only.

How values are checked

Every option value, whether it comes from the command line, a config file or the default, passes these checks in this order. The first failing check produces the error message. Args and defaults skip some steps, as noted below the list.

  1. The shape: a single value, or a list or mapping for "multiple", "csv", "hash" and "objectlist" options. Values of a list or mapping are checked one by one in the following steps.

  2. The type's check, including the type-specific keys ("min, max", "mustExist").

  3. The type's conversion, for example '007' to the number 7.

  4. The "valid" list, compared with the converted value.

  5. The "lazyValid" check, called with the converted value.

  6. For the value that is finally used: preparation, which creates missing paths for "createPathIfMissing".

Args pass steps 2, 3 and 6. Defaults pass steps 1 to 5 when GetOptions builds the spec, and step 6 when a parse uses them.

CONFIG FILES

Enabling config files

Config files are enabled with the "config" key on the top level:

config => {
    format      => 'yaml',
    paths       => ['/etc/backup.yaml', '~/.config/backup.yaml'],
    defaultPath => '~/.config/backup.yaml',
    autoload    => 1,
},
format

Mandatory. The file format: yaml (or yml) or json. The YAML format needs the module YAML::XS; without it, GetOptions dies with a spec error. The JSON format uses JSON::PP, which comes with Perl. Other formats can be added, see Getopt::Pad::Config::Format.

paths

An arrayref of files that are loaded automatically, in this order, when the command line has no --config option. Files that do not exist are skipped silently. The default is an empty list.

defaultPath

The file that a bare --config (without a path) loads. It is not loaded automatically: add it to paths as well if it should be.

autoload

Whether paths is loaded when the command line has no --config option. The default is true. With a false value, config files are only read when the user asks for one with --config.

A leading ~ is replaced with the value of $HOME in the paths that locate config files: paths, defaultPath, and the paths given to --config and --create-default-config. Other forms such as ~user are not expanded. A ~ in an option value, from the command line or from a config file, is never expanded.

The config block adds two automatic options to the top level, which are also accepted on every command level (they are inherited, see "inherit"): "--config [PATH]" and "--create-default-config PATH". No level may declare an option or alias named config or create-default-config.

Where config files are loaded from

Without --config on the command line, and with autoload on, every existing file in paths is loaded in order. A later file overrides an earlier one option by option, on every level: an option set in both files gets its value from the later file, an option set in only one of them keeps that value. As always, the whole value of an option is replaced; the entries of a list or a mapping are not merged.

With --config PATH on the command line, only that file is loaded; paths is ignored. Parsing then continues normally. A file given with --config must exist, otherwise that is the user error config file 'PATH' does not exist.

A bare --config loads defaultPath. If the spec has no defaultPath, that is the user error --config without a path, and the spec sets no defaultPath. Because the value of --config is optional, it takes the next word as the path unless that word starts with a dash (a lone - is taken as the path, though). So in tool --config input.txt, input.txt is the config path, not an arg. Write --config= to load defaultPath when an arg or command follows: tool --config= input.txt. For a config file whose name starts with a dash, write --config=-name.yaml or --config ./-name.yaml.

--config may be given on any level, before or after the command words.

File layout

A config file is a mapping of group names (see "group") to mappings of option names to values. Options without a group are in the group Options. Use the option's primary name, not an alias.

On a level with commands, the key commands holds one section per command, and each section has the same layout, down to any depth. For this spec:

GetOptions(
    options => {
        'log-level' => { type => 'string', default => 'info' },
        owner       => { type => 'string', group => 'Target' },
    },
    commands => {
        document => {
            options  => { notes => { type => 'file' } },
            commands => {
                create => {
                    options => { format => { type => 'string', valid => ['pdf', 'docx'] } },
                },
            },
        },
    },
    config => { format => 'yaml', paths => ['~/.tool.yaml'] },
);

a config file that sets every option looks like this in YAML:

Options:
  log-level: debug
Target:
  owner: dave
commands:
  document:
    Options:
      notes: /srv/docs/notes.txt
    commands:
      create:
        Options:
          format: pdf

and like this in JSON:

{
  "Options": { "log-level": "debug" },
  "Target": { "owner": "dave" },
  "commands": {
    "document": {
      "Options": { "notes": "/srv/docs/notes.txt" },
      "commands": {
        "create": { "Options": { "format": "pdf" } }
      }
    }
  }
}

Every key is optional: a file sets only what it contains. An inherited option (see "inherit") is set in the groups of the level that declares it, not in the sections of the commands below.

Values in config files

Config values pass the same checks as command line values (see "How values are checked"). In addition:

  • A key without a value (YAML ~, or nothing after the colon; JSON null) is the user error no value given. For "hash" and "objectlist" options it is reported as the wrong shape instead (expected a mapping of keys to values, expected a list of mappings). An explicitly empty string ('' in YAML, "" in JSON) is a value: a string option reads it as the empty string.

  • A list or a mapping for a single-value option is the user error expected a single value, not a list or mapping.

  • Values are used as they are: a ~ or $HOME in a value is not expanded.

  • flag and bool options take the YAML or JSON boolean values true and false (written without quotes), or 1 and 0, also as the strings "1" and "0". An explicitly empty string reads as 0. Any other string, such as yes, on or the quoted "true", is rejected.

  • counter options take a non-negative integer.

  • A JSON true or false given to an option that is not a flag or bool reaches the reader as a JSON::PP::Boolean object, which stringifies to 1 or 0.

  • A "multiple" option takes a list or a single value. For a "csv" option a single value is split at commas; a list is taken as it is.

  • A "hash" option takes a mapping, an "objectlist" option a list of mappings.

For these options:

options => {
    tag    => { type => 'string', multiple => 1 },
    color  => { type => 'string', multiple => 1, csv => 1 },
    define => { type => 'string', hash => 1 },
    server => { type => 'string', objectlist => 1 },
},

a config file sets values like this:

Options:
  tag: [red, blue]                # multiple: a list
  color: red, green               # multiple with csv: a single value is split
  define: { os: linux }           # hash: a mapping
  server:                         # objectlist: a list of mappings
    - { host: alpha, port: 80 }
    - { host: beta }

How config files are checked

Every loaded file is checked completely, whichever command the command line selects. Each of these is a user error that names the file and, for command sections, the command:

  • a file that is not a mapping, or that the format cannot parse,

  • a group, a commands key or a command section that is not a mapping,

  • an unknown command name under commands,

  • an unknown option, an automatic option, or an option under the wrong group.

Only the values that are used are checked: values in the sections of the levels that the command line selects, and among those only the ones that neither the command line nor a later config file overrides. A mustExist path in the section of another command is not checked, and createPathIfMissing creates nothing for it.

An empty file is not an empty mapping. An empty YAML file (or one with only comments) is the user error config file 'PATH' must contain a mapping of group names. For JSON, an empty file is a parse error; write {} for a JSON file that sets nothing.

Writing a starter config file

$ tool --create-default-config ~/.tool.yaml
Wrote default config to /home/user/.tool.yaml

(Here the shell has replaced ~ before the program sees it; the message shows the path as the program received it.)

The automatic option --create-default-config PATH writes a config file that contains the default of every option that has one, on every level, in the layout described above, and exits with status 0. Groups and command sections without any defaults are left out. The values are the checked and converted defaults, so an int default of '007' is written as 7.

The option refuses to overwrite an existing file, and to write through a symbolic link (config file 'PATH' already exists). It works even when the rest of the command line is incomplete, for example without a required option or command. Formats that cannot write files (see Getopt::Pad::Config::Format) make it fail with config format 'NAME' cannot write config files. The built-in yaml and json formats can.

Encoding

Config files are read and written as UTF-8. Their values are Perl character strings. See "CAVEATS" for values from the command line.

AUTOMATIC OPTIONS

Getopt::Pad adds these options by itself. --config only selects a config file. The other automatic options stop the parse: as soon as the level they are given on has been read, they print their output to STDOUT and exit with status 0. Nothing else is checked first, so tool --help works even when a required option is missing. Only a malformed command line on the same level (before or after the option) or on an outer level, such as an unknown option, wins over them. Levels after it are not read at all: tool --help scan --bogus prints the help of the top level.

--help

On every level. Prints the help of the level it is given on. It is not listed in the help output itself.

--version

On the top level only. Prints the program name and version (see the spec key "version"). It is not listed in the help output. Every result object also has a version method that does the same, see "Methods".

--create-completions SHELL

On the top level only. Prints a completion script for bash or zsh (see "SHELL COMPLETION"). Listed in the help group Completion.

--config [PATH]

Only with a "config" block. Loads the given config file instead of the automatic ones, or defaultPath without a path (see "Where config files are loaded from"). Listed in the help group Config. Accepted on every level.

--create-default-config PATH

Only with a "config" block. Writes a config file with the spec's defaults (see "Writing a starter config file"). Listed in the help group Config. Accepted on every level.

The names of the automatic options cannot be used for your own options on the levels where the automatic options exist. There are no short forms: -h is not --help unless you declare it yourself (see "Adding -h as a short form of --help" in Getopt::Pad::Cookbook). The automatic options have no readers.

HELP OUTPUT

--help prints a usage text built from the spec. For the program in the "SYNOPSIS" it looks like this:

# backup [options] source
# Copy a directory to a backup location.

## Arguments
   <source>                    [REQ] Directory to back up [Path]

## Completion
   --create-completions <>     Print a completion script for this shell to
                               STDOUT and exit
                                   Valid   = [ bash, zsh ]

## Options
   --[no-]compress             Compress the backup; --no-compress turns it
                               off
                                   Default = 1
   --exclude <>                Pattern of files to skip; repeat for more
                               patterns
   --keep <>                   Number of backups to keep
                                   Default = 7
   --target <>                 [REQ] Directory the backup is written to
                               [Path]
   --verbose                   Print more details; repeat for even more
                               (-vv)

Layout

The first line shows the program name (the file name of $0), the command path, [options] when the level has visible options, <command> when it has commands, and the args: required args by name, optional args in brackets, a multiple arg (see "ARG SPECS") followed by .... The second line is the "description", if any.

Arguments

One entry per arg.

Option groups

One section per "group", in alphabetical order. Within a group, the level's own options come first, in alphabetical order of their keys, followed by the automatic options and then by the inherited options. Hidden options are left out.

Commands

On levels with commands: every command with its "description".

Examples

The "examples", if any.

Entries

An option is shown by its primary name. Aliases are not shown. The name is followed by a placeholder for its value:

--name                 flag, counter
--[no-]name            bool
--name <>              takes a value
--name <a,b,...>       csv
--name <key=value>     hash
--name <N.key=value>   objectlist

The text next to the name consists of, in this order: [REQ] for a required option or arg, [has to exist] or [created if missing] (for options only; args do not show them), the "help" text, and the type label ([URL], [Path], [File Path] or the "typehint"). Below it, a Valid line lists the values of a static "valid" arrayref, and a Default line shows the "default". A list default is shown as a, b, a hash default as k=v, k2=v2, and an objectlist default as 0.host=a, 0.port=80.

Width and color

The help text is wrapped to the width in the environment variable COLUMNS, if that is a positive integer. Otherwise, when the output is a terminal and Term::ReadKey is installed, the terminal width is used; otherwise the width is 100 columns. The help samples in this documentation are shown with COLUMNS=76.

On a terminal, the output is colored, unless the environment variable NO_COLOR is set to a non-empty value or TERM is dumb.

There is no spec key for the width or the colors. A program that wants a fixed width or no colors sets $ENV{COLUMNS} or $ENV{NO_COLOR} before it calls GetOptions.

Printing the help from your program

The result object's help method prints the help text of its level to STDOUT and exits with status 0:

$opt->help if !$opt->files->@*;     # nothing to do: show the help

After a user error, the help is printed to STDERR instead, below the error message.

SHELL COMPLETION

Every program that uses Getopt::Pad can print a completion script for bash and zsh:

$ tool --create-completions bash > ~/.local/share/bash-completion/completions/tool
$ tool --create-completions zsh  > ~/.zsh/completions/_tool

For zsh, the directory must be in your $fpath. You can also source the script from ~/.bashrc or ~/.zshrc. The script registers completion for the program's file name (the file name of $0 when the script is generated), so install the program under that name in your PATH. The bash script needs bash 4.0 or later.

What is completed

  • the command names of the current level, when the level has commands,

  • the option names of the current level after a -, including inherited options, --no-NAME for bool options whose name is longer than one letter, and short names as -x; hidden options are not offered,

  • the values of the option's "valid" list, as the value of an option (--level d<TAB>) or after = (--level=d<TAB>). For a "hash" or "objectlist" option the values are completed after the KEY= part, for a "csv" option after the last comma. A valid coderef is called on every tab press, so the candidates are always current,

  • file names for file options and args, directory names for dir options and args, using the shell's own completion.

How it works

The script contains no knowledge of your program's options. Every time the user presses tab, it runs the program again with the environment variables GETOPT_PAD_COMPLETE (the shell name) and GETOPT_PAD_COMPLETE_INDEX (the position of the word under the cursor) set, and the words typed so far as arguments. GetOptions recognizes this, prints the candidates and exits with status 0, so nothing after the GetOptions call runs. The script therefore never needs to be regenerated when the spec changes.

Everything your program does before it calls GetOptions runs on every tab press. Call GetOptions as early as possible, and do not do anything with side effects before it.

RESULT OBJECT

GetOptions returns an object with one reader per option and arg of the top level (see "Reader names"). There are no methods to set values: calling a reader with an argument is an error. Lists and mappings are returned as ordinary Perl references, which belong to this result object; if your program changes their contents, the reader returns the changed data from then on. Other parses are not affected.

The object is an instance of a class that Getopt::Pad generates for the spec. That class inherits from Getopt::Pad::Result; do not rely on its name.

Values by option kind

Option or arg                      Given                  Not set anywhere,
                                                          no default
---------------------------------  ---------------------  -----------------
flag                               1 (0 from config)      undef
bool                               1 or 0                 undef
counter                            number of times        undef
single value                       the value              undef
multiple option, multiple arg      arrayref of values     []
hash option                        hashref                {}
objectlist option                  arrayref of hashrefs   []
optional arg                       the value              undef

Numbers from int and float options are returned as numbers.

Methods

Every result object has these methods in addition to its readers:

command

The name of the command selected on this level, or undef when the level has no commands or none was given.

subcommand

The result object of the selected command's level, or undef.

help

A method, not a reader: prints the help text of this level to STDOUT and exits with status 0.

version

A method, not a reader: prints the program name and version to STDOUT and exits with status 0, like the automatic --version option.

See Getopt::Pad::Result for details.

Reserved names

No option or arg may have a reader name that the result object already uses. These names are a spec error: command, subcommand, help, version, helper, reservesReader, new, can, isa, DOES, VERSION, META, BUILDARGS, DESTROY and AUTOLOAD (helper and reservesReader are internals of the result class). Currently croak is rejected as well, which is a known bug. The error message is reader 'NAME' collides with a built-in result method.

Aliases have no readers, so they may use these names, except help (on every level) and version (on the top level), which are automatic options. To offer --command on the command line, make it an alias of an option with another primary name: 'cmd|command' gives the reader cmd.

ERRORS AND EXIT STATUS

User errors

A mistake on the command line or in a config file is a user error. GetOptions prints it to STDERR as ERROR: MESSAGE (with ERROR in red on a terminal), followed by an empty line and the help text of the level the error belongs to, and exits with status 2:

$ backup photos
ERROR: missing required option '--target'

# backup [options] source
# Copy a directory to a backup location.
...

Only the first error is reported, with one exception: all problems the command line parser finds on one level, such as several unknown options, are reported together in one message, separated by ; . All messages are listed under "DIAGNOSTICS".

Spec errors

A mistake in the spec is a bug in the program, not a user error. GetOptions dies with a message that starts with Getopt::Pad spec: and ends with the file and line of your GetOptions call, for example:

Getopt::Pad spec: option 'keep': default value: 'seven' is not an integer at backup line 11.

Messages from the checks of a command's level start with the command path, such as Getopt::Pad spec: command 'image resize': .... These include the checks between the options and args of that level: duplicate names and aliases, reader clashes, the order of args and inherit. Messages about the keys of one option or arg spec (unknown keys, type, default, bounds, valid, typehint) name only the option or arg, not the command, and unknown option type names neither. GetOptions checks the complete spec on every call, including all commands, before it looks at the command line, so a broken spec fails on the first run, whatever the command line is. The exception is an error raised by a "valid" coderef that returns something other than an arrayref, which is only noticed when the coderef is called.

Exceptions thrown by your own coderefs ("valid", "lazyValid") are not caught; they propagate out of GetOptions.

Exit status (exit code)

Exit status 0

After an automatic option (--help, --version, --create-completions, --create-default-config), after answering a shell completion request, and when your program calls help or version on a result object.

Exit status 2

After a user error.

GetOptions itself never exits with any other status. When it returns, your program continues normally. A spec error is an uncaught die, which ends the program with a non-zero status chosen by Perl from $! or $? (see "die" in perlfunc): usually 255, but it can be any value, including 2. Do not use the exit status to tell spec errors from user errors.

DIAGNOSTICS

This section lists the messages of Getopt::Pad, so you can search for the text you see. Upper case words stand for the actual values. In the messages that start with Option or Unknown option, NAME is the option as the user typed it, without dashes (Unknown option: taget for --taget). The other command line messages name an option by its primary name with two dashes (option '--keep': ...). Config file and spec messages use the primary name without dashes (config value for 'keep': ...).

Command line errors

These are printed as ERROR: MESSAGE with the help text, and the program exits with status 2.

Unknown option: NAME

The option does not exist on this level. Check the spelling (names must not be abbreviated), whether it belongs to another level, and whether it comes before the command word (see "Options and commands").

Option NAME requires an argument

The option takes a value, but the command line ends after it. (In this message and the next one, "argument" means the option's value.)

Option NAME does not take an argument

A value was given to a flag, bool or counter with --name=value.

Option NAME, key "KEY", requires a value

A "hash" or "objectlist" option was given a word without =. Write the word as KEY=VALUE (--define os=linux), or for an objectlist option as INDEX.FIELD=VALUE.

missing required option '--NAME'

A "required" option was not set on the command line or in a config file.

missing required argument <NAME>

A required arg (see "ARG SPECS") is missing.

unexpected extra argument 'WORD'

The command line has more words than the level has args.

missing command, expected one of: NAMES

The level has commands, and none was given. See "commandRequired".

unknown command 'WORD', expected one of: NAMES

The word after the options of a level with commands is not one of its commands.

option '--NAME': PROBLEM

The value of an option failed a check. PROBLEM is one of the value problems listed below.

argument <NAME>: PROBLEM

The value of an arg failed a check.

Value problems

These are the PROBLEM part of option '--NAME': PROBLEM, argument <NAME>: PROBLEM and config value for 'NAME': PROBLEM.

'VALUE' is not an integer
'VALUE' is not a number

The value of an int or float option is not a number of that kind.

'VALUE' is not a finite number

A float value spelled inf, infinity or nan (in any case, with an optional sign).

VALUE is smaller than the minimum of MIN
VALUE is larger than the maximum of MAX

The value is outside the "min, max" bounds.

file 'PATH' does not exist
directory 'PATH' does not exist

The option has "mustExist", and the path is not an existing file or directory. The message is the same when the path exists but is of the other kind.

cannot create file 'PATH': REASON
cannot create directory 'PATH': REASON

"createPathIfMissing" could not create the path.

'VALUE' is not a URL

The value is not of the form scheme://..., see "url".

'VALUE' is not one of: VALUES

The value is not in the "valid" list.

'VALUE' is not a valid value

The "lazyValid" check returned false.

'VALUE' contains an empty item

A "csv" value has an empty item, such as a,,b.

empty key

A "hash" option was given =VALUE without a key.

key 'KEY': PROBLEM

The value for KEY of a "hash" option failed a check.

invalid key 'KEY', expected INDEX.FIELD=VALUE

A word of an "objectlist" option does not have the form INDEX.FIELD=VALUE.

missing index N

The indices of an "objectlist" option have a gap.

entry N: PROBLEM

An entry of an "objectlist" option failed a check. PROBLEM is key 'KEY': ... for a value, empty key, or, in a config file, expected a mapping of keys to values for an entry that is not a mapping.

'VALUE' is not a boolean (use true or false)

A config file gives a flag or bool option a value that is not a YAML or JSON boolean (true, false), 1 or 0 (as a number or a string), or an explicitly empty string.

'VALUE' is not a count

A config file gives a counter option a value that is not a non-negative integer.

no value given

A config file gives an option no value (YAML ~ or a key with nothing after the colon, JSON null). An explicitly empty string ('', "") is a value.

expected a single value, not a list or mapping
expected a mapping of keys to values
expected a list of mappings

A config value or a default does not have the option's shape (see "Values in config files" and "default").

expected a list of values

The default of a "multiple" option is not an arrayref. This is a spec error (option 'NAME': default value: expected a list of values); config files do not produce it.

Config file errors

These are user errors as well (ERROR: MESSAGE, exit status 2).

config file 'PATH' does not exist

The file given with --config does not exist.

--config without a path, and the spec sets no defaultPath

A bare --config needs "defaultPath".

cannot read config file 'PATH': REASON

The file exists but cannot be read, for example because of its permissions.

config file 'PATH': MESSAGE

The format could not parse the file. MESSAGE comes from the parser.

config file 'PATH' must contain a mapping of group names

The top level of the file is not a mapping, or the YAML file is empty.

config file 'PATH': group 'GROUP' must contain a mapping of option names
config file 'PATH': group 'GROUP' of command 'COMMAND' must contain a mapping of option names
config file 'PATH': 'commands' must contain a mapping of command names
config file 'PATH': 'commands' of command 'COMMAND' must contain a mapping of command names
config file 'PATH': command 'COMMAND' must contain a mapping of group names

A part of the file does not have the layout described under "File layout".

config file 'PATH': unknown option 'NAME' in group 'GROUP'
config file 'PATH': unknown option 'NAME' in group 'GROUP' of command 'COMMAND'

The level has no option with this primary name, or the name belongs to an automatic option.

config file 'PATH': option 'NAME' belongs to group 'GROUP', not 'OTHER'
config file 'PATH': option 'NAME' of command 'COMMAND' belongs to group 'GROUP', not 'OTHER'

The option is in the wrong group.

config file 'PATH': unknown command 'COMMAND', expected one of: NAMES

A section under commands is not a command of that level. COMMAND is the command path of the unknown section, such as image crop.

config value for 'NAME': PROBLEM

A value failed a check, see "Value problems".

config file 'PATH' already exists

--create-default-config does not overwrite files.

cannot write config file 'PATH': REASON

--create-default-config could not create the file.

config format 'NAME' cannot write config files

The format has no dump method, see Getopt::Pad::Config::Format.

Spec error messages

These make GetOptions die with Getopt::Pad spec: MESSAGE at FILE line LINE. Messages from the checks of a command's level start with command 'PATH': ; messages about the keys of a single option or arg spec do not name the command.

unknown key(s): KEYS
option 'NAME': unknown key(s): KEYS
arg 'NAME': unknown key(s): KEYS
config: unknown key(s): KEYS

A key is misspelled, or not allowed at this place (for example config in a command spec, or min for a string option).

'options' must be a hash reference
'args' must be an array reference
'commands' must be a hash reference
'examples' must be an array reference
'argv' must be an array reference
each example must be a hash with 'text' and 'args'

A spec key has the wrong kind of value.

option 'KEY': spec must be a hash reference
arg: spec must be a hash reference

An option or arg spec is not a hashref.

option 'KEY': invalid name 'NAME'
arg: missing or invalid 'short' name
invalid command name 'NAME'

A name does not start with a letter or contains characters other than letters, digits, underscores and dashes.

option 'NAME': reader 'READER' collides with a built-in result method
arg 'NAME': reader 'READER' collides with a built-in result method

See "Reserved names".

option 'A' and option 'B' both map to reader 'READER'
arg 'A' and option 'B' both map to reader 'READER'

Two options or args of one level have the same reader, see "Reader names".

option 'NAME': name 'N' is already used by option 'OTHER'
option 'NAME': name 'N' is already used by an alias of option 'OTHER'
option 'NAME' inherited from LEVEL: name 'N' is already used by option 'OTHER'

Two options of one level share a name or alias, or an option reuses a name of an inherited option. LEVEL is the top level or command 'PATH'.

option 'NAME' collides with the automatic --NAME option

An option or alias uses the name of an automatic option, see "AUTOMATIC OPTIONS". For an option whose primary name is help or version, the message is reader 'NAME' collides with a built-in result method instead.

unknown option type 'TYPE' (known: NAMES)

See "TYPES".

option 'NAME': required and default are mutually exclusive
option 'NAME': multiple requires a value-taking type, not 'TYPE'

(also for hash and objectlist)

option 'NAME': multiple and hash are mutually exclusive

(and the other combinations of multiple, hash and objectlist)

option 'NAME': csv requires multiple
option 'NAME': inherit requires commands on the same level
option 'NAME': valid must be an array or code reference
option 'NAME': the valid coderef must return an array reference
option 'NAME': lazyValid must be a code reference
option 'NAME': typehint must be a non-empty string
arg 'NAME': typehint must be a non-empty string
option 'NAME': default value: PROBLEM

The default failed a check, see "Value problems".

option 'NAME': min must be a number, not 'VALUE'
option 'NAME': max must be a number, not 'VALUE'
option 'NAME': min MIN is larger than max MAX

(For args, these and the other messages about one arg start with arg 'NAME': instead.)

option 'NAME': mustExist and createPathIfMissing are mutually exclusive
arg 'NAME': type 'TYPE' cannot be used for a positional arg
arg 'NAME': multiple is only allowed on the last arg
arg 'NAME': a required arg cannot follow an optional one
args and commands are mutually exclusive on one level
commandRequired without commands
group 'commands' is reserved for the command sections of config files
config: expects a hash reference
config: missing 'format'
config: 'paths' must be an array reference
unknown config format 'NAME' (known: NAMES)
config format 'yaml' requires the YAML::XS module

See "CONFIG FILES".

command 'PATH': expects a hash reference

A command spec is not a hashref, as in commands => { add => 1 }. A command without options or args is written add => {}.

option key must be a non-empty string

An option key is the empty string.

Other errors

These are not reported as Getopt::Pad spec: messages, but they also point at a mistake in the program.

Odd name/value argument for subroutine 'Getopt::Pad::GetOptions'

Perl's own message: GetOptions was called with an odd number of arguments. Usually a value is missing, or the spec was passed as a hashref (GetOptions($spec) instead of GetOptions(%$spec)).

Getopt::Pad: option type name 'NAME' is already registered by CLASS
Getopt::Pad: config format name 'NAME' is already registered by CLASS

registerType or registerFormat was called with a class that uses a name another class has already registered. See Getopt::Pad::Type and Getopt::Pad::Config::Format.

Getopt::Pad: option type class CLASS does not provide a NAMES list
Getopt::Pad: config format class CLASS does not provide a NAMES list

The registered class has no NAMES constant. Before this check, the class's module file is loaded, so if the class is defined in the script itself, the message can be Can't locate My/Type/Foo.pm in @INC ... (for the class My::Type::Foo) instead.

Getopt::Pad: no help renderer attached to this result

help or version was called on a result object that was not created by GetOptions.

ENVIRONMENT

COLUMNS

The width the help output is wrapped to, when set to a positive integer.

NO_COLOR

When set to a non-empty value, the help and error output is never colored.

TERM

When set to dumb, the help and error output is never colored.

HOME

Replaces a leading ~ in config file paths.

GETOPT_PAD_COMPLETE, GETOPT_PAD_COMPLETE_INDEX

Set by the generated completion scripts. When GETOPT_PAD_COMPLETE is set, GetOptions answers a completion request instead of parsing (see "SHELL COMPLETION"). Do not set them yourself.

EXTENDING

Getopt::Pad has two extension points. Both work the same way: you write an Object::Pad class that inherits from a base class, list the names it answers to in a NAMES constant, and register it.

Option types

See Getopt::Pad::Type. Registered with Getopt::Pad::Type::registerType('My::Type').

Config file formats

See Getopt::Pad::Config::Format. Registered with Getopt::Pad::Config::Format::registerFormat('My::Format').

A registered name is available to every spec in the program. A name that another class has already registered (built-in or not) cannot be taken over; the registration dies.

EXAMPLES

The distribution contains runnable scripts in its examples/ directory. Each one prints the values of its result object, so you can try different command lines. The header comment of each script lists command lines to try.

01-basic.pl

Options with groups, defaults and a valid list, and a required arg.

02-types.pl

One option per built-in type.

03-commands.pl

Nested commands, an inherited option and a JSON config file with command sections.

04-custom-type.pl

A custom type that accepts only even numbers.

05-custom-format.pl

A custom config format for TOML files.

06-value-shapes.pl

multiple, csv, hash and objectlist options.

07-config.pl

Config files: the autoload chain, defaultPath and --create-default-config.

08-checks.pl

valid lists and coderefs, lazyValid, float bounds, mustExist, createPathIfMissing, hidden and typehint.

The source of the examples is at https://github.com/davenonymous/perl-getopt-pad/tree/master/examples.

CAVEATS

GetOptions exits the program

On user errors and for the automatic options, GetOptions calls exit. Code after the call only runs for a valid command line. To test a command line that should fail, run your program in a separate process; see "Testing a command line" in Getopt::Pad::Cookbook.

Command line values are not decoded

Words from the command line reach your program as Perl receives them: byte strings, not decoded character strings. Values from config files are decoded from UTF-8. For non-ASCII values the two sources then differ, and a valid list with non-ASCII values written in a use utf8 program matches config values but not command line values. If your program handles non-ASCII input, decode @ARGV before calling GetOptions:

use Encode qw(decode);
@ARGV = map { decode('UTF-8', $_) } @ARGV;

or run perl with the -CA switch.

Aliases are not shown in the help

The help output lists an option by its primary name only. Mention short aliases in the "help" text if users should know them.

The order in the help output is alphabetical

Groups and the options within a group are sorted alphabetically, not in the order of the spec.

REQUIREMENTS

Perl 5.26 or later, Object::Pad 0.818 or later, Getopt::Long 2.50 or later, Feature::Compat::Try and JSON::PP.

Optional: YAML::XS for YAML config files, and Term::ReadKey for wrapping the help output to the terminal width.

SEE ALSO

Getopt::Pad::Tutorial, Getopt::Pad::Cookbook, Getopt::Pad::Result, Getopt::Pad::Type, Getopt::Pad::Config::Format

Getopt::Long, which Getopt::Pad uses to split the command line.

Object::Pad, which the result objects and extension classes are built with.

AUTHOR

davenonymous <perl@davenonymous.com>

COPYRIGHT AND LICENSE

Copyright 2026 davenonymous

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.