The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Getopt::Auto - Option framework for command-line applications


    use Getopt::Auto;


Getopt::Auto provides an easy way to organize a script to handle whatever option mechanism it requires.

For each option --foo you provide a subroutine sub foo{...}. The sub is called every time --foo appears on the command line. Values for the option are taken from @ARGV.

If you don't provide a subroutine for --foo, then $options{'--foo'} is set.

Using Getopt::Auto

  • In the POD (Plain Old Documentation).

  • In the use statement.

  • Forgetaboutit.


Here's an example I'll reference later.

    use Getopt::Auto;
    our %options;

    $VERSION  = '1.0';
    sub add { $count += shift @ARGV; }
    $count += $options{'--inc'};
    print "Count: $count\n";


    =head2 -a, --add - Add integer to count.

    The integer argument is not checked.

    =head2 --inc - Bump count by 1


When is executed, --add 2 --inc -a 3
    Count: 6

Working from POD

OK, so we're all excellent Perl authors, which means that our scripts have careful and extensive documentation as POD. In particular all of the options are there. Just check that the options are described in one of these ways, and you can enjoy all of the benefits of Getopt::Auto.

Use =head2, =head3, =head4 or =item, thus:

    =head2 -a, --add - Add integer to count.

    The integer argument is not checked.

There are several things to note.

  • I've used =head2 in the example.

    Wherever I do this, you may substitute =head3, =head4 or =item as you wish.

  • Notice the structure of the =head2 line. It's important.

    To begin, we have the options -a and --add. There are some options (pun intended) here. Three styles are supported, and they may be mixed.

    "long" (--gnu-style)
    "short" (-oldstyle)
    "bare" (CVS-style, myprogram edit foo.txt)

    What follows the option(s) is 'space(s) dash(es) space(s)'; at a minimum ' - '. This makes the =head2 command into an option registration. Without it, it's just another =head2. The 'dash space' separates the option from the remainder of the line, which is called the "Short Help". If there's just 'space dash space' and nothing else, then there is no "Short Help".

    Options may be combined. For example, =head2 -a, --add.

  • Finally, there's the "Long Help". There may be one or more paragraphs, or there may be none. It's up to you. The "Long Help" stops at the next POD command.

The "Short Help" and "Long Help" are used by the built-in --help option. See "Help and Version".

use Getopt::Auto([...])

Getopt::Auto can work from lists passed in the use statement. It expects a reference to a list of lists. Each list consists of four elements.

  • The name of the option, with the requisite leading dashes, if any

  • The short help. One line, no newlines

  • The long help, paragraphs separated by newlines

  • A CODE reference for the subroutine that processes the option

The "Example" could be coded with no POD.

    use Getopt::Auto([
                      ['--add', 'Add integer to count.', "The integer argument is not checked.
                      ['-a', 'Add integer to count.', undef, \&add],
                      ['--inc','Bump count by 1', undef, undef]

There is no requirement that the CODE reference have the same name as the option, nor that it be unique. It can also be undef if you wish only to have %options set. The command line is treated the same irrespective of how the options are defined. Please use undef for any list elements you don't need.

You may have multiple [] groupings, and you may also include "Advanced Options". However, you may not use a variable, because a variable won't be assigned at the time Getopt::Auto::import is called.

This method can be used in conjunction with "Working from POD".


This feature must be turned on using the "Advanced Usage" configuration option, findsub.

So, you're not so careful about your POD? Or, perhaps its too soon for POD? (Hah!) Never fear, you're covered. Just provide an option subroutine, or check %options. This works because when Getopt::Auto comes across what appears to be an option while processing the command line, it checks to see if there's a corresponding sub. If you have a sub whose name is the same as a piece of valid data that may be entered on the command line, the data will be treated as an option, so be careful.

Where's the POD?

Getopt::Auto looks for POD in three places, in this order:

The current file
Thie current file with the extension '.pod' substituted for .pm, .pl or .t.
The current file with the extension '.`pod' added, if there's no .pm, .pl or .t.

Scanning stops the first time there is any success. This means that you can't split the =head2 POD over files. Notice that although we talk about, all of this works for as well. Or example.t, for that matter.

There's a (small) exception to this. Scanning for VERSION does not interrupt the scanning for POD. See "Help and Version".

It's OK for there to be no POD at all, so there's no error message if, for example, your has no POD and there's no foo.pod.

What's an Option?

Here's our example, once more.

    =head2 -a, --add - Add integer to count.

    The integer argument is not checked.

Getopt::Auto scans your script (In the CHECK block: see perlmod). Once the =head2 is stripped, we're left with a line of text. Some options (-a, --add), followed by 'space(s) dash(es) space(s)'; at a minimum ' - '. This makes the =head2 command into an option registration. Without it, it's just another =head2. Notice that there are two options here, one short and one long, seperated by a comma. You can have more than just two. Or just one.

Getopt::Auto checks to see if there's a subroutine in the current package that is defined for each option. See "Option Subroutines".

It's not a requirement that every option have a subroutine. See "Options Without Subroutines".

If, in the example, there's no sub a{...}. In order to simplify things for you, Getopt::Auto assumes that if you are listing several options under a single =head2, you probably wish to process them with the same sub. Hence, any options that don't have a sub are assigned the next one found that does. sub add{...} in the example.

The 'dash space' separates the option from the remainder of the line, which is called the "Short Help". If there's just 'space dash space' and nothing else, then there is no "Short Help".

Short Help

The short help is everything on the line after "dash space". If it's not defined, then this =head2 does not describe an option.

Long Help

The paragraph(s) that follow the =head2 up to the next POD command are the long help. There may be none. The long help is copied verbatim from the POD, without formatting.

Registered Option

Options discovered in POD are referred to as registered, Options from "use Getopt::Auto([...])" are also registered. Otherwise, anything on the command line that looks like an option will get an error message. These are called unregistered options.

Option Subroutines

The name of an option subroutine is computed from the name of the option.

  • Strip leading dashes

  • Convert embedded dashes to underscores

--foo-bar expects sub foo_bar{...}.

Command Line Processing

Now we've scanned the POD and/or included the data from /use Getopt::Auto([...]). Getopt::Auto sees @ARGV before the program begins execution. (In the INIT block: see perlmod.) As it processes the elements, it finds options and executes the indicated actions. The non-option elements are shifted off and retained. The processing subroutines may manipulate @ARGV in any way, but it's expected that they will just shift off their arguments, which will be the first elements of @ARGV. When option processing ends, the retained elements are replaced (unshifted) for the program to see.

So, using "Example" again, when --add 2 9999 --inc -a 3 abcd, begins execution, it sees (9999, abcd) in @ARGV, 2 and 3 having been shifted off by add().

Values specified by "="

This would be --add=24 rather than --add 24. If Getopt::Auto encounters this construct, it strips out the "=" and add() will see "24" in $ARGV[0]. Note that as this usage provides an argument, there must be a subroutine associated with the option.

Cease and desist

There's a convention in @ARGV processing that uses a bare "--" or "-" to signal the end to option processing. Getopt::Auto supports this, and you can use either! --add 2 -- 9999 --inc -a 3 abcd 

leaves (9999 --inc -a 3 abcd) in @ARGV. Command-line processing was turned off by the '--' that follows --add 2.

Execution Order

When coding an option subroutine, take into consideration that it will be executed in the context of an INIT block. (See perlmod.) A side-effect of this (or the intended effect, if you prefer) is that none of what one might see as "normal" variable initializations are performed. For example, add this to

    my $var = 'abcd';
    sub printvar {
        print "\$var is '$var'\n";

    =head2 --printvar - Print the value of $var

and so, --printvar
    $var is ''

as $var is undefined at that point.

It's easy to get caught by this, especially when converting code from other option schemes. There are ways to work around the problem.

Use write-only subroutines

This is general advice for option subroutines. Think of them as write-only. In other words, they should not read anything from their environment, other than @ARGV.

Use a flag variable

Have foo() set a "foo was called" global (not initialized, of course) and call foo() (now renamed) at a convenient time.

Don't use a sub foo for --foo

At a convenient time do: _foo() if exists $options{'--foo'}.

Use an init subroutine.

If the "Configuration" hash has init => \&your_init_sub, then your_init_sub will be called at the in the INIT block before any option processing. Needed initializations could be performed there.

Options Without Subroutines

An option that does not have an associated subroutine will cause $options{'option'} in the use-ing package to be incremented. (Please specify "our %options") and note the quotes. The option is inserted in the %options hash as --add or -a. Omit the quotes and Perl will try to pre-increment your sub add{...}!

A note about interaction with your code.

If you say our %options

The hash will be managed as above.

If you say nothing

You'll get a %main::options defined for you. If you use %options in other ways, that could result in confusion.

If you say my %options

%main::options will be assigned as above, and will be accessible (unless you use strict) until your my %options is executed.

Mixing Option Styles

Getopt::Auto is tolerant of mixed bare, short and long option styles. There's one thing to look out for. If you say -foo when you registered --foo, you will not get a call to sub foo(). Instead, you get the default processing for short options.

Short Option Default Processing

If -foo is not Registered Getopt::Auto treats -foo as one use of -f and two of -o. So the processing looks for sub f{...} and sub o{...}. If they are defined, they are called. Otherwise, you will find $options{'f'} == 1, and $options{'o'} == 2 in the calling package.

Now, if this was not sufficiently complicated, immagine if you executed as -fad. -fad is an unregistered, short option. So, in addition to complaints about -f and -d not being registered options (see "Option Errors"), sub add will be executed because of the default processing for -fad. You can use "Tracing" to follow the workings of this case. One more thing. Because -fad, -f and -d did not have an associated subs, they will all show up in @ARGV.

All of this complexity may be avoided by selecting the "Configuration" option nobundle.

Invalid Options

Options, (short or long) that are not registered are unshifted into @ARGV. There will also be an error message. See "Option Errors". Bare "options" are indistinguishable from command-line data, so they can't be flagged as errors.

Advanced Usage


Getopt::Auto may be invoked with an hash ref. These are the recognized keys, also referred to as "Configuration Options". Note that with the exception of init all of the options are global, in the sense that they are executed processing the command line so in which module they might have been specified is irrelevant.

  • noshort => 1 - Ignore short options

  • nolong => 1 - Ignore long options

  • nobare => 1 - Ignore bare options

  • nobundle => 1 - Don't de-group short options

  • nohelp => 1 - Don't provide help for unregistered options

  • oknotreg => 1 - Do not complain if unregistered options are found on the command line

  • okerrors => 1 - Do not exit if there are errors parsing @ARGV)

  • init => \&your_sub - Called before processing command line

    This subroutine will be called by Getopt::Auto in the INIT block before it scans the command line for options. If multiple packages are involved, the init subroutines are executed in the order processed by Perl.

  • findsub => 1 - Enable using unegistered options

    If --foo is not registered but there is a sub foo{...}, it will be called. This implies oknotreg => 1 .

  • trace => 1 - Enable tracing.


If an option style is turned off by one of noshort, nolong or nobare, it is referred to as restricted.


Setting the environment variable GETOPT_AUTO_TRACE to 1 with cause Getopt::Auo to trace its actions to STDOUT. If you say trace => 1 in the configuration hash, this overrides GETOPT_AUTO_TRACE. To turn off tracing from the shell, set GETOPT_AUTO_TRACE to 0.


Getopt::Auto runs before your script starts. So what if you need to debug it? You will notice several lines in the code:

    #$DB::single = 2;      ## no critic (ProhibitPackageVars)

Delete the '#' to have the Perl debugger stop at that point. So why are these lines commented out? So you won't have to step over them when debugging your script.

Despite this, when you load your script in the Perl debugger, you will see:


Why is this? Because this part of Getopt::Auto is actually the first part of your script, as it's in the INIT block. At this point, you're in Getopt/, not the file you're attempting to debug. So, just enter 'c' to continue from the INIT block, and you're on your way. To set breakpoints in your code, either use the Perldb f command to move focus to the appropriate source file, or use the Perldb commands n or r, which will take you to the first executable statement in the code that uses Getopt::Auto. Sorry for the inconvenience.

Extended Example

Check out scripts/ in the distribution for an extended example.

Help and Version

Getopt::Auto automatically provides help and version options, following the style (long, short or bare) that is (numerically) the most common in the POD or the use statement. And if there's no POD? Then the default is to recognize --help and --version.

help and version are output to STDERR.

--help lists the commands available and the short help messages. If a --help --option is given for a option with "Long Help", the longer message will be printed instead. Of course options discovered by findsub won't appear.

--version displays your program name, plus VERSION. This means you must set $VERSION = whatever in your application. (It's not a problem if you don't). Getopt::Auto gets this by scanning the calling package for the first occurrence of $VERSION, and then extracts a version number matching [\d\.]+. If you have another standard, well ....

The help function will exit 0 after execution. --help

    This is version 1.0 -a - Add integer to count. --add - Add integer to count. [*] --help - This text --inc - Bump count by 1 --version - Prints the version number

    More help is available on the topics marked with [*]
    Try --help --foo
    This is the built-in help, exiting

Suppose you want to have your own --help and/or --version? An obvious way to do the would be to check $options{'--help'} in your script. Regrettably, there's a conflict between this way of doing things and the built-in help. However, if you create a sub help{...} instead, it will work fine.

Pod::Usage does a nice job of turning your POD into help.

Here's a simple usage().

        sub usage {
            pod2usage( -verbose => 2 );
            exit 0;


Getopt::Auto tries not to complain, but sometimes life is just too hard! Output is to STDERR.

From use Getopt::Auto

These happen when the import method has a problem. No additional processing by Getopt::Auto takes place. Getopt::Auto will exit 1 before parsing the POD.

  • Getopt::Auto: Option specification [list element] should be a reference

    We need either a reference to an HASH or ARRAY.

  • Getopt::Auto: Option list is incompletely specified

    It needs 4 elements. See "use Getopt::Auto([...])".

  • Getopt::Auto: Must be use-d with: no args, an HASH ref or an ARRAY ref

    Whatever you said, it wasn't one of these.

  • Getopt::Auto: Option <option> is unknown

    You've said something like use Getopt::Auto({foobar=1})>, and we don't know about foobar.

From @ARGV Processing

If there are any errors in this phase, Getot::Auto will exit 1 at the end of processing unless you have set the "Configuration" option okerror. The number of errors may be obtained by calling Getopt::Auto::get_errors (which is not exported).

  • Getopt::Auto: <option> is not a registered option

    Getopt::Auto has found <option> (--foobar) on the command line, but you did not make it a "Registered Option". If this is the way you like to do things, you need to use Getopt::Auto({oknotreg=1}).

    If you have an unregistered option, you will also get help, if it is available. This means the subroutine that you specified for --help, for -h or the builtin help if neither are available. To avoid all of this, say use Getopt::Auto({nohelp=1}).

    Getopt::Auto: <option> (from <some option>) is not a registered option

    Getopt::Auto has found <option> (-foo) on the command line, but you did not make it a "Registered Option". However, there were some subs defined, so there was partial execution. Notice that the example refers to a short option, as this situation can only happen there. Suppose you defined sub o{...} but not sub foo{...}. The default processing for a short option that does not have an associated sub is to examine the individual letters. In this case, sub o{...} was found, and executed. The error message will report -f from -foo as unregistered.

    Again, if this is the way you like to do things, you need to use Getopt::Auto({oknotreg=1}).

  • Getopt::Auto: To use <option> with "=", a subroutine must be provided

    The only way to interpret "--foo=24" is that a sub foo{...} exists that will extract "24" from @ARGV.


Getopt::Auto may be required, but as it depends on Perl calling its import() subroutine to process arguments to the statement, none of these will work. Of course, if you use import Getopt::Auto as well, all will be well.

In version 1.0, the option subroutine is called after the program exits (in the END block) with the contents of @ARGV at that point as parameters. Getopt::Auto then exits, meaning that only one option subroutine can be processed.

In the present version, the option subroutines are called called before program execution begins (in the INIT block). The subroutine is called with no parameters. Rather, it is expected to inspect @ARGV and remove whatever it uses. Multiple option subroutine calls are supported.

In the END block, the 1.0 code executes main::default() if that subroutine is present. This has been retained for compatibility, but will be removed in future versions unless someone makes a fuss.


Version 2.0


Simon Cozens, who had the original idea.


Geoffrey Leach mailto://, who has hacked on it unmercifully.


Bruce Gray, Aristotle Pagaltzis and Ian Tegbo for their contributions. All errors are the responsibility of the maintainer.


Config::Auto, Getopt::Long, perlmod, Pod::Usage


Copyright (C) 2003-2009, Simon Cozens.

Copyright (C) 2010, Geoffrey Leach.

This module is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl 5.10.For more details, see the full text of the licenses at, and