Getopt::ArgParse(3pm)

πŸ“¦
version 1.0.6 Β· 2 versions
  • 1.0.6 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 1.0.6 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– Getopt::ArgParse πŸ’–

okay so this is the Getopt::ArgParse(3pm) page from the User Contributed Perl Documentation, bestie, and it's a whole personality. grab a snack πŸ“, we're parsing command line arguments and we're doing it cutely.


✨ NAME ✨

Getopt::ArgParse β€” parsing command line arguments with a richer and more user-friendly API interface, similar to Python's argparse but with perlish extras πŸͺπŸ’…

In particular, the module provides the following features:

  • generating usage messages
  • storing parsed arg values in an object, which can be also used to load configuration values from files and therefore the ability for applications to combine configurations in a single interface
  • A more user-friendly interface to specify arguments, such as argument types, argument values split, etc.
  • Subcommand parsing, such svn <command>
  • Supporting both flag based named arguments and positional arguments

like. it does SO much. main character module fr fr πŸ‘‘


πŸ¦‹ VERSION πŸ¦‹

version 1.0.6 β€” that's the one, no cap.


🌸 SYNOPSIS 🌸

okay here's the whole vibe in one go, copy it, run it, live it:

use Getopt::ArgParse;

$ap = Getopt::ArgParse->new_parser(
       prog        => 'MyProgramName',
       description => 'This is a program',
   epilog      => 'This appears at the bottom of usage',
);

# Parse an option: '--foo value' or '-f value'
$ap->add_arg('--foo', '-f', required => 1);

# Parse a boolean: '--bool' or '-b' using a different name from
# the option
$ap->add_arg('--bool', '-b', type => 'Bool', dest => 'boo');

# Parse a positonal option.
# But in this case, better using subcommand. See below
$ap->add_arg('command', required => 1);

# $ns is also accessible via $ap->namespace
$ns = $ap->parse_args(split(' ', 'test -f 1 -b'));

say $ns->command; # 'test'
say $ns->foo;     # false
say $ns->boo;     # false
say $ns->no_boo;   # true - 'no_' is added for boolean options

# You can continue to add arguments and parse them again
# $ap->namespace is accumulatively populated

# Parse an Array type option and split the value into an array of values
$ap->add_arg('--emails', type => 'Array', split => ',');
$ns = $ap->parse_args(split(' ', '--emails a@perl.org,b@perl.org,c@perl.org'));
# Because this is an array option, this also allows you to specify the
# option multiple times and splitting
$ns = $ap->parse_args(split(' ', '--emails a@perl.org,b@perl.org --emails c@perl.org'));

# Below will print: a@perl.org|b@perl.org|c@perl.org|a@perl.org|b@perl.org|c@perl.org
# Because Array types are appended
say join('|', $ns->emails);

# Parse an option as key,value pairs
$ap->add_arg('--param', type => 'Pair', split => ',');
$ns = $ap->parse_args(split(' ', '--param a=1,b=2,c=3'));

say $ns->param->{a}; # 1
say $ns->param->{b}; # 2
say $ns->param->{c}; # 3

# You can use choice to restrict values
$ap->add_arg('--env', choices => [ 'dev', 'prod' ],);

# or use case-insensitive choices
# Override the previous option with reset
$ap->add_arg('--env', choices_i => [ 'dev', 'prod' ], reset => 1);

# or use a coderef
# Override the previous option
$ap->add_args(
       '--env',
       choices => sub {
               die "--env invalid values" if $_[0] !~ /^(dev|prod)$/i;
       },
   reset => 1,
);

# subcommands
$ap->add_subparsers(title => 'subcommands'); # Must be called to initialize subcommand parsing
$list_parser = $ap->add_parser(
        'list',
        help => 'List directory entries',
        description => 'A multiple paragraphs long description.',
);

$list_parser->add_args(
  [
    '--verbose', '-v',
     type => 'Count',
     help => 'Verbosity',
  ],
  [
    '--depth',
     help => 'depth',
  ],
);

$ns = $ap->parse_args(split(' ', 'list -v'));

say $ns->current_command(); # current_command stores list,
                            # Don't use this name for your own option

$ns =$ap->parse_args(split(' ', 'help list')); # This will print the usage for the list command
# help subcommand is automatically added for you
say $ns->help_command(); # list

# Copy parsing
$common_args = Getopt::ArgParse->new_parser();
$common_args->add_args(
  [
    '--dry-run',
     type => 'Bool',
     help => 'Dry run',
  ],
);

$sp = $ap->add_parser(
  'remove',
  aliases => [qw(rm)],           # prog remove or prog rm
  parents => [ $command_args ],  # prog rm --dry-run
);

# Or copy explicitly
$sp = $ap->add_parser(
  'copy',
  aliases => [qw(cp)],           # prog remove or prog rm
);

$sp->copy_args($command_parser); # You can also copy_parsers() but in this case
                                 # $common_parser doesn't have subparsers

that's a LOT of slay in one code block and yes, every line of it is doing something. 🫢


πŸ“– DESCRIPTION πŸ“–

(fun fact: the original heading literally says "DESCRIPTIOIN" β€” we don't talk about it, we love her anyway πŸ’€)

So: Getopt::ArgParse, Getopt::ArgParse::Parser and related classes together aim to provide user-friendly interfaces for writing command-line interfaces. A user should be able to use it without looking up the document most of the time β€” and honestly? iconic behavior. It lets applications define argument specifications and it will parse them out of @AGRV by default (yes bestie, the doc says @AGRV, we're keeping it, no notes πŸ™ˆ) or a command line if provided. It implements both named arguments, using Getopt::Long for parsing, and positional arguments. The class also generates help and usage messages.

The parser has a namespace property, which is an object of ArgParser::Namespace. The parsed argument values are stored in this namespace property. Moreover, the values are stored accumulatively when parse_args() is called multiple times.

Though inspired by Python's argparse and names and ideas are borrowed from it, there is a lot of difference from the Python one. fr fr, it's not a copy, it's a remix.


🧚 Getopt::ArgParser::Parser 🧚

This is the underlying parser that does the heavylifting. πŸ’ͺ

Getopt::ArgParse::Parser is a Moo class.

πŸ› οΈ Constructor πŸ› οΈ

my $parser = Getopt::ArgParse->new_parser(
  help        => 'short description',
  description => 'long description',
);

The former calls Getopt::ArgParser::Parser->new to create a parser object. (another little naming easter egg in the original β€” ArgParser vs ArgParse, we stan a chaotic typo πŸ’…)

The parser constructor accepts the following parameters.

🌟 All parsers are created with a predefined Bool option --help|-h. The program can choose to reset it, though.
  • prog β€” The program's name. Default $0.
  • help β€” A short description of the program.
  • description β€” A long description of the program.
  • namespace β€” An object of Getopt::ArgParse::Namespace. An empty namespace is created if not provided. The parsed values are stored in it, and they can be refered to by their argument names as the namespace's properties, e.g. $parser->namespace->boo. See also Getopt::ArgParse::Namespace
  • parser_configs β€” The Getopt::Long configurations. See also Getopt::Long
  • parents β€” Parent parsents, whose argument and subparser specifications the new parser will copy. See copy() below
  • error_prefix β€” Customize the message prefixed to error messages thrown by Getop::ArgParse, default to 'Getopt::ArgParse: '
  • print_usage_if_help β€” Set this to false to not display usage messages even if --help is on or the subcommand help is called. The default behavior is to display usage messages if help is set.

πŸ’« add_arg, add_argument, add_args, and add_arguments πŸ’«

$parser->add_args(
  [ '--foo', required => 1, type => 'Array', split => ',' ],
  [ 'boo', required => 1, nargs => '+' ],
);

The object method, arg_arg or the longer version add_argument, defines the specification of an argument. (arg_arg!! the original really said that and I'm obsessed 😭) It accepts the following parameters.

add_args or add_arguments() is to add multiple multiple arguments. (multiple multiple. we said what we said. πŸ’€)

  • name or flags β€” Either a name or a list of option strings, e.g. foo or -f, --foo.
    • If dest is not specified, the name or the first option without leading dashes will be used as the name for retrieving values. If a name is given, this argument is a positional argument. Otherwise, it's an option argument.
    • Hyphens can be used in names and flags, but they will be replaced with underscores '_' when used as option names. For example:
$parser->add_argument( [ '--dry-run', type => 'Bool' ]);
# command line: prog --dry-run
$parser->namespace->dry_run; # The option's name is dry_run
  • A name or option strings are following by named parameters.
  • dest β€” The name of the attribute to be added to the namespace populated by parse_args().
  • type => $type β€” Specify the type of the argument. It can be one of the following values:
    • Scalar β€” The option takes a scalar value.
    • Array β€” The option takes a list of values. The option can appear multiple times in the command line. Each value is appended to the list. It's stored in an arrayref in the namespace.
    • Pair β€” The option takes a list of key-value pairs separated by the equal sign '='. It's stored in a hashref in the namespace.
    • Bool β€” The option does not take an argument. It's set to true if the option is present or false otherwise. A 'no_bool' option is also available, which is the negation of bool().

For example:

$parser->add_argument('--dry-run', type => 'Bool');

$ns = $parser->parse_args(split(' ', '--dry-run'));

print $ns->dry_run; # true
print $ns->no_dry_run; # false
  • Count β€” The option does not take an argument and its value will be incremented by 1 every time it appears on the command line.
  • split β€” split should work with types 'Array' and 'Pair' only.

split specifies a string by which to split the argument string e.g. if split => ',', a,b,c will be split into [ 'a', 'b', 'c' ].When split works with type 'Pair', the parser will split the argument string and then parse each of them as pairs.

  • choices or choices_i β€” choices specifies a list of the allowable values for the argument or a subroutine that validates input values.

choices_i specifies a list of the allowable values for the argument, but case insenstive, and it doesn't allow one to use a subroutine for validation.

Either choices or chioces_i can be present or completely omitted, but not both at the same time. 🚨

  • default

okay bestie we are literally mid-bullet here 😭 default is about to get its whole moment and the rest of this page keeps going β€” part 2 has you, hold on 🫢

Like, the value you get when the argument just… isn't on the command line at all. And heads up bestie: only one value is allowed for scalar argument types β€” Scalar, Count, and Bool. That's the whole vibe. πŸ’…

  • required β€” whether the command-line option can be left out or not (optionals only, so don't come for me). This does literally nothing for the Bool and Count types. A named option that's required gets marked with a question mark ? in the generated usage, like:
--help, -h             ? show this help message and exit
Note: this parameter is ignored for Bool and Count types, because they already have default values. Slay, no extra work needed. ✨
  • help β€” a little brief description of what the argument actually does. Its whole personality in one line. πŸŽ€
  • metavar β€” a name for the argument in usage messages. It's the little stand-in that shows up in the usage text. πŸ‘‘
  • reset β€” set reset to override an existing definition of an option. It clears the value in the namespace too, so no stale leftovers. 🧹
  • nargs β€” Positional option only β€” this only tells the parser how many arguments to consume. The program still has to specify the right type to actually get the result it wants. Like, nargs is not out here doing type magic, okay? πŸ™ˆ
    • n β€” 1 if not specified
    • ? β€” 1 or 0
    • + β€” 1 or more
    • * β€” 0 or many. And this one will consume the rest of the arguments. The whole buffet. πŸ“

🌸 parse_args 🌸

$namespace = $parser->parse_args(@command_line);

This object method takes a list of arguments, or @ARGV if you didn't give it any, parses them for values, and stashes those values in the namespace object. Iconic behaviour honestly.

A few things about parse_args() that are genuinely worth knowing:

First: parsing for Named Arguments is done by Getopt::Long. Not us. We're just standing on their shoulders. 🫢

Second: parsing for positional arguments happens after the named-argument parsing. It consumes whatever is still left sitting on the command line. Leftovers = its problem now.

Finally: the Namespace object is accumulatively populated. If you call parse_args() multiple times to parse a bunch of command lines, it's the same namespace object getting populated over and over, not a fresh one. Which means:

  • For Scalar and Bool options: the previous value gets overwritten. Bye. πŸ’€
  • For Pair and Array options: values get appended. More is more. ✨
  • For a Count option: it adds on top of the previous value. Stacking. πŸ”₯

In fact, the program can choose to pass an already populated namespace when it creates a parser object. Why? So the program can pre-load values into a namespace from conf files before it ever parses the command line. Main character pre-loading energy. πŸ’–

And finally finally: it does NOT display usage messages if the argument list is empty. Which, lowkey, may be contrary to a lot of other argument-parsing implementations out there. Not us though. We're built different. 😭


πŸ¦‹ argv πŸ¦‹

@argv = $parser->argv; # called after parse_args

Call this after parse_args() has been invoked to get the unconsumed arguments. It's up to the application to decide what to do if there's a surplus of arguments β€” like, that's a you problem, not a parser problem. 🫠


✨ The Namespace Object ✨

The parsed values live in a namespace object. Any class with these three methods can be the Namespace class:

  • A constructor new()
  • set_attr(name => value)
  • get_attr(name)

The default one is Getopt::ArgParse::Namespace. It uses autoload to give you a readonly accessor method using dest names to get at parsed values. However β€” this is not required for a user-defined namespace. So inside the implementation, $namespace->get_attr($dest) should always be used. No cap. πŸ’…


πŸŽ€ Subcommand Support πŸŽ€

Real talk: only one level of subcommand parsing is supported. Subcommands cannot have subcommands. No subcommand inception. That's the rule, bestie. πŸ’€

Call add_subparsers() first to initialize the current parser for subcommand support. A help subcommand is created as part of that initialization. The help subcommand has these options:

required positional arguments:
     COMMAND      ? Show the usage for this command optional named
arguments:
    --help, -h     ? show this help message and exit
    --all, -a      ? Show the full usage

Call add_parser() to add a subparser for each subcommand. Then use the parser object that add_parser() hands back to add the options to that subcommand. Easy.

Once subcommand support is on: if the first argument is not a flag (i.e. it doesn't start with a dash -), the parser's parse_args() will treat it as a subcommand. Otherwise, the parser just parses for the defined arguments like normal. Vibe check on that first argument, basically. 🌈

The namespace's current_command() will hold the subcommand after parsing successfully. πŸ‘‘

Unlike arguments, subparsers cannot be reset. Sorry. πŸ™ˆ


add_subparsers

$parser->add_subparsers(
  title       => 'Subcommands',
  description => 'description about providing subcommands',
);

add_subparsers must be called to initialize subcommand support. Non-negotiable. πŸ’…

  • title β€” a title message to mark the beginning of the subcommand usage in the usage message.
  • description β€” a general description that appears about the title.

add_parser

$subparser = $parser->add_parser(
   'list',
   aliases     => [qw(ls)],
   help        => 'short description',
   description => 'a long one',
   parents => [ $common_args ], # inherit common args from
                                # $common_args
);
  • $command β€” the first argument is the name of the new command.
  • help β€” a short description of the subcommand.
  • description β€” a long description of the subcommand.
  • aliases β€” an array reference containing a list of command aliases.
  • parents β€” an array reference containing a list of parsers whose specification will be copied by the new parser.

get_parser

$subparser = $parser->get_parser('ls');

Return the parser for parsing the $alias command if it exists. If it doesn't… well. 🌸


πŸ’œ Copying Parsers πŸ’œ

A parser can copy argument specification, or subcommand specification, from existing parsers. A use case for this is when the program wants all subcommands to share a common set of arguments. Very communal. Very giving. 🫢

copy_args

$parser->copy_args($common_args_parser);

Copy argument specification from the $parent parser. πŸ“‹

copy_parsers

$parser->copy_parsers($common_args_parser);

Copy parser specification for subcommands from the $parent parser. πŸ“‹

copy

$parser->copy($common_args_parser);

Copy both arguments and subparsers. The whole package deal. ✨


format_usage

$usage = $parser->format_usage;

Return the formatted usage message for the whole program, as an array reference. πŸ“

$parser->print_usage;

Print the usage message returned by format_usage(). Simple as. πŸ–¨οΈ

format_command_usage

$usage = $parser->format_command_usage($subcommand);

Return the formatted usage message for the command, as an array reference. πŸ“

$parser->print_command_usage($subcommand);

Print the usage message returned by format_command_usage(). And here's the little detail: if $command is not given, it will first try to use $self->namespace->help_command (which will be present for the help subcommand), and then $self->namespace->current_command. Fallback chain, slay. πŸ’…


🌟 SEE ALSO 🌟

  • Getopt::Long
  • Python's argparse

🌸 AUTHOR 🌸

Mytram <mytram2@gmail.com> (original author)

πŸ¦‹ CONTRIBUTORS πŸ¦‹

  • Robbin Bonthond (rbonthond@github)
  • Adam Pfeiffer (apinco@github)

This software is Copyright (c) 2015 by Mytram.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)

And that's a wrap on the whole page, bestie! πŸŽ€ This one came out of the perl v5.34.0 toolchain, dated 2022-06-14, and it's the Getopt::ArgParse(3pm) man page β€” go forth and parse your arguments like the icon you are. πŸ’…βœ¨πŸ«Ά