Getopt::Yath(3pm)

πŸ“¦ version 2.000011, in ubuntu stonking

✨ NAME ✨

Getopt::Yath(3pm) β€” Option processing yath style. πŸ’… it's a User Contributed Perl Documentation joint, and bestie, it's literally the getopt processor yath uses, iykyk.

🌸 DESCRIPTION 🌸

okay so this is the getopt processor that yath uses. and ngl, it should work perfectly fine outside of yath as well. no cap. πŸ’–

πŸ¦‹ SYNOPSIS πŸ¦‹

DEFINING OPTIONS

so like, here's how you define options, bestie:

package My::Package;
use Getopt::Yath;

# Include options from other modules that use Getopt::Yath
include_options(
    'Some::Options::Package',
    ...,
);

# an option group is basically a way to specify common parameters for all
# options defined in the codeblock.
option_group {category => 'Human readable category', group => 'settings_group'} => sub {

    # In addition to the fields specified here, all the fields from the
    # 'option_group' above are included:
    option verbose => (
        type => 'Bool',                 # This is a boolean type, it does not take an argument

        # Optional fields
        short => 'v',                   # Allow -v in addition to --verbose
        default => 0,                   # What value to use if none is specified (booleans default to 0 anyway)
        from_env_vars => ['VERBOSE'],   # If the $VERBOSE environment variable is set, this will be set to true.
        set_env_vars  => ['VERBOSE'],   # If this is set to true it will also set the $VERBOSE environment variable

        description => "This turns on verbose output",
    );

    option username => (
        type => 'Scalar',           # Scalar type, requires an argument

        # Optional
        short => 'U',               # Allow: -U Bob
        alt => ['user', 'uname'],   # Allow: --user Bob, --uname Bob
        from_env_vars => ['USER'],  # Get the value from the $USER env var if it is not provided.
        default => sub { "bob" . rand(100) }, # If none is specified, and the env var is empty, generate a default.

        description => "This sets your username",
    );

    # Other options
    ...
};

basically option_group is like a vibe container for common params, and option defines each one. slay. πŸ’…

PARSING OPTIONS

now to actually parse some args, bestie:

my $parsed = parse_options(
    ['-v', '--user', 'fred', 'not_an_opt', '--', '--will-not-process'],    # Normally you might pass in \@ARGV
    skip_non_opts => 1,                                                    # Skip non-opts, that is any argument that does not start with a '-' it will just skip.
    stops         => ['--'],                                               # Stop processing
    no_set_env    => 1,                                                    # Do not actually change %ENV
    groups        => { ':{' => '}:' },                                     # Arguments between the :{ and }: will be captured into an arrayref, they can be used as option values, or stand-alone
);

and $parsed is a Getopt::Yath::State object, which is giving main character energy:

$parsed->cleared;     # {} - Options that were cleared with --no-opt
$parsed->skipped;     # ['not_an_opt'] - Skipped non options
$parsed->settings;    # Blessed as Getopt::Yath::Settings
                      #   ->settings_group (Blessed as Getopt::Yath::Settings::Group)
                      #       ->verbose  == 1
                      #       ->username == 'fred'
$parsed->stop;        # '--' - We stopped at '--', if there was no '--' this would be undef
$parsed->remains;     # ['--will-not-process'] - Stuff after the '--' that we did not process
$parsed->modules;     # {'My::Package' => 2} - Any module that provided options that were seen
$parsed->env;         # {'VERBOSE' => 1} - Environment variables that would have been set

obsessed with how clean that is. πŸ’–

GENERATING COMMAND LINE HELP OUTPUT:

you can also generate help output, periodt:

sub help {
    print options()->docs('cli');
}

help();

Produces:

           Human readable category
            --username ARG,  --username=ARG,  --user ARG,  --user=ARG,  --uname ARG
            --uname=ARG,  -U ARG,  -U=ARG,  --no-username
             This sets your username

             Can also be set with the following environment variables: USER

            --verbose,  -v,  --no-verbose
             This turns on verbose output

             Can also be set with the following environment variables: VERBOSE

             The following environment variables will be set after arguments are processed: VERBOSE

GENERATING POD:

and for the POD girlies:

sub pod {
    print options()->docs('pod', head => 2); # The '2' specifies what heading level to use
}

pod();

Produces:

           =head2 Human readable category

           =over 4

           =item --username ARG

           =item --username=ARG

           =item --user ARG

           =item --user=ARG

           =item --uname ARG

           =item --uname=ARG

           =item -U ARG

           =item -U=ARG

           =item --no-username

           This sets your username

           Can also be set with the following environment variables: C<USER>

           =item --verbose

           =item -v

           =item --no-verbose

           This turns on verbose output

           Can also be set with the following environment variables: C<VERBOSE>

           The following environment variables will be set after arguments are processed: C<VERBOSE>

           =back

πŸ’– EXPORTS πŸ’–

  • $opts = options() β€” this returns a Getopt::Yath::Instance object. it's literally the main character holding all your defined options and doing all the real work under the hood. πŸ’…
  • $parsed = parse_options(\@ARGV) / $parsed = parse_options(\@ARGV, %PARAMS) β€” this processes an arrayref of command line arguments and returns a Getopt::Yath::State object. if there's a problem parsing, like invalid options in the array, exceptions get thrown. so like, be careful bestie. see Getopt::Yath::State for the full list of accessors on the returned object.

available parameters that affect parsing are:

  • stops => \@STOP_LIST / stops => ['--'] β€” a list of strings that, if encountered, stop the parsing process. the string it stopped at is available via $parsed->stop. any unparsed arguments after the stop are available via $parsed->remains. this is mostly useful for supporting the -- option. periodt.
  • groups => \%GROUP_BORDERS / groups => { ':{' => '}:' } β€” arguments between the specified start and end tokens get grouped together into an arrayref. slay.
  • stop_at_non_opts => BOOL β€” makes parsing stop at any non-option. a non-option here is any argument that does not start with a -. the item stopped at is available via $parsed->stop with the remaining arguments available via $parsed->remains.
  • skip_non_opts => BOOL β€” skips any non-option encountered. a non-option is any argument that does not start with -. all skipped items are available via $parsed->skipped.
  • skip_invalid_opts => BOOL β€” skips any invalid option encountered. this includes any argument that starts with - but is not a valid option. all skipped items are available via $parsed->skipped.
  • stop_at_invalid_opts => BOOL β€” causes parsing to stop at any invalid option. this includes any argument that starts with - but is not a valid option. the item stopped at is available via $parsed->stop with the remaining arguments available via $parsed->remains.
  • no_set_env => BOOL β€” set this to true to prevent any modifications to %ENV. $parsed->env will contain the environment variable changes that would have been made. note: the env accessor is always populated even if %ENV is modified directly. πŸ’–
  • include_options('Options::Module::A', 'Options::Module::B', ...) β€” lets you build libraries of Getopt::Yath options and include them as needed. options from the specified libraries get merged into the current package's options. obsessed.
  • option_group \%fields => sub { ... } / option_group {group => 'my_group'} => sub { option ...; ... } β€” creates a group of options with common parameters. iconic.
  • option TITLE => \%SPECIFICATION / option TITLE => (type => '+My::Type', ...) / option TITLE => (type => 'Getopt::Yath::Option::Type', ...) / option TITLE => (type => 'Type', ...) β€” used to define a single option. you must specify an option NAME and 'type', which must be a valid Getopt::Yath::Option subclass. The TITLE is used to produce default values for the 'field' and 'name' fields, both of which can be specified directly if the automatic values aren't sufficient. 'field' gets the value of title with dashes replaced by underscores. 'name' gets the value of title with underscores replaced with dashes. Most of the time you can just list the type as the part after the last :: in Getopt::Yath::Option::TYPE. You can also specify Getopt::Yath::Option::TYPE or Getopt::Yath::Option::TYPE::SubType directly. However if you need to use a module that is not in the Getopt::Yath::Option:: namespace you will need to prefix the module with a + to indicate that. iykyk.
  • option_post_process sub { ... } / option_post_process $weight, sub { ... } / option_post_process $weight, $applicable, sub { ... } β€” register a callback to run after all options have been parsed. the callback receives the Getopt::Yath::Instance object and the parse state hashref as arguments. $weight controls execution order (lower weights run first, default is 0). $applicable is an optional coderef that determines whether this post-processor should run; if provided it receives the post-process entry, the instance, and the settings object. if used inside an option_group block, the group's applicable is inherited when none is specified.
option_post_process 100 => sub {
    my ($instance, $state) = @_;
    # Do something after all options are parsed
};
  • category_sort_map(%map) β€” set the sort order for option categories in documentation output. categories with lower values are listed first. by default, NO CATEGORY - FIX ME is sorted to 99999 (last).
category_sort_map(
    'Display Options' => 1,
    'Runner Options'  => 2,
    'Logging Options' => 3,
);

πŸ‘‘ OPTION TYPES AND SPECIFICATIONS πŸ‘‘

REQUIRED WITH NO DEFAULTS

  • title β€” this is the first argument to option(). it's used to build the default values for both field and name.
  • group => "group_name" β€” name of the field to use in the options hash under which the option will be listed:
$parsed->{options}->{$group}->{$field_name} = $val
  • type => 'TypeName'
  • type => 'Getopt::Yath::Option::TypeName'
  • type => '+My::Custom::Type' β€” bestie, this one has to be a valid Getopt::Yath::Option subclass, no exceptions πŸ’…

And here's the whole type roster, one by one:

  • Scalar β€” takes a scalar value, and yeah, a value is required. You can hit it as --opt VAL or --opt=val. Wanna wipe it? --no-opt clears the value. 🧼
  • Bool β€” it's either on or off, simple as. --opt turns it on, --no-opt turns it off. Default is off unless you pass in a default parameter. 🎚️
  • Count β€” an integer, and the default is to start at 0. --opt increments the counter, --no-opt resets the counter back to zero, and --opt=VAL lets you specify a desired count directly. πŸ”’
  • List β€” can take multiple values. --opt VAL appends a value to the list. --no-opt will empty the list. And if you give it a split_on parameter then a single use can set multiple values β€” like, if split_on is set to , and you pass --opt foo,bar, then both foo and bar get added to the list. πŸ“
  • Map β€” expects all values to be key=value pairs and produces a hashref. So --opt foo=bar will set $h{foo} = 'bar'. And again, with a split_on parameter a single use can set multiple values β€” if split_on is set to , and you pass --opt foo=bar,baz=bat, the result is $h{foo} = 'bar'; $h{baz} = 'bat'. πŸ”‘
  • Auto β€” this type has an 'autofill' value that gets used if no argument is provided to the parameter, i.e. just --opt. But you can also hand it a specific value using --opt=val. Heads up though: it DOES NOT support --opt VAL, and that will most likely result in an exception 😭. So don't do that.
  • AutoList β€” combo meal of 'Auto' and 'List' types πŸ”. The no-arg form --opt adds the default value(s) to the list. The --opt=VAL form adds additional values.
  • AutoMap β€” combo of 'Auto' and 'Map'. The no-arg form --opt adds the default key+value pairs to the hash. The --opt=KEY=VAL form adds additional values.
  • PathList β€” like List, but the values are treated as file paths and may contain shell-style wildcards (globs) which get expanded. So --opt 'lib/*.pm' will expand to all matching files. ✨
  • AutoPathList β€” like PathList but with autofill support. The no-arg form --opt adds the autofill paths, while --opt=path adds a specific path.
  • BoolMap β€” matches several --OPTION-XXX and --no-OPTION-XXX options based on a regex pattern, populating a hashref where each matched key gets a true or false value depending on the --no- prefix. Requires a pattern attribute. 🧩

πŸ’– REQUIRED WITH SANE DEFAULTS πŸ’–

  • field => "field_name" β€” the name of the field to use in the group hash for the result of parsing arguments.
$parsed->{options}->{$group}->{$field_name} = $val

Default is to take the title value and replace any dashes with underscores.

  • name => "option-name" β€” the primary name for the option --option-name.

Default is to take the title value and replace any underscores with dashes.

  • trace => [$caller, $file, $line] β€” this normally resolves to the place option() was called. You can manually override it with a custom value, but fr fr you should rarely ever need to.
  • category => "Human Readable documentation category" β€” when producing POD or command line documentation, options get sorted into "categories", which should be the human readable version of the group field.

Default is "NO CATEGORY - FIX ME".

  • description => "Explanation of what the option controls" β€” document what the option controls or does.

Default is 'NO DESCRIPTION - FIX ME'.


πŸŽ€ OPTIONAL πŸŽ€

  • short => 's' β€” specify a short flag to use. This is how you get those single-dash single-letter options. And here's every flavor of how it lands:
    • -s β€” if no argument is required, this form is available.
    • -s=VAL β€” if an argument is allowed, this form is available.
    • -sVAL β€” if an argument is allowed, and this form isn't directly disabled by the type. (Types can override allows_shortval() to return false to forbid this form β€” as of right now Getopt::Yath::Option::Bool and Getopt::Yath::Option::Count disable this form.)
    • -sss β€” so far only the Getopt::Yath::Option::Count type makes use of this. It lets you stack the flag multiple times after a single dash to increment the count. πŸ”₯
  • alt => \@LIST / alt => ['alt1', 'alt2'] β€” specify alternate or alias names that can be used to set or toggle a field. Like --alt1 or --alt2 foo. πŸ‘―
  • prefix => "a-prefix" β€” specify a prefix to attach to the name, and to any alternate names. This is mainly useful when specifying an option group:
option_group {prefix => 'foo'} => sub {
    option bar => (
        type => "Bool",
    );
};

That would then be used as --foo-bar.

  • module => 'My::Module' β€” specify the module the argument should be associated with. This defaults to the caller, so usually you don't need to specify it. It's mainly used in the case of plugins we only want to load if the option is used.
  • no_module => BOOL β€” default is 0. When this is set to true, the module name is not used.
  • applicable => sub { my $options = shift; ... ? 1 : 0 } β€” this one lets you dynamically show/hide options. When it returns false, the option will not be available. πŸ™ˆ
  • initialize => $scalar / initialize => sub { ... } β€” initialize the value to this before any arguments are parsed. This is mainly used so that Getopt::Yath::Option::Map can start with an empty hash, and Getopt::Yath::Option::List can be initialized to an empty arrayref.

It can be a simple scalar (string or number, not a reference), or it may be a codeblock that returns anything you want. Only 1 item should be returned β€” extra values will result in undefined behavior, no cap. For a map this should return an empty hashref, for a list it should return an empty arrayref.

  • clear => $scalar / clear => sub { ... } β€” similar to initialize, but this is used when clearing the value. For things like 'Map' this should return a hashref, etc.
  • default => $scalar / default => sub { ... } β€” set a default to use if no value is provided at the command line.

It can be a simple scalar (string or number, not a reference), or it may be a codeblock that returns anything you want.

Most options will only accept a single default value. Getopt::Yath::Option::Map and Getopt::Yath::Option::List support a list of defaults for setting key/value pairs, or adding items to an array.

These are valid for anything:

default => 'foo',
default => 123,
default => sub { "hi" }

This is valid for an Getopt::Yath::Option::Map:

default => sub { return ('foo' => 'bar') }

This is valid for an Getopt::Yath::Option::List:

default => sub { return (1, 2, 3, 4) }
  • autofill => $scalar / autofill => sub { ... } β€” this is used for Getopt::Yath::Option::Auto and similar. It's the value used if the command line option is provided, but no value is provided with it.

It can be a simple scalar (string or number, not a reference), or it may be a codeblock that returns anything you want.

Most options will only accept a single autofill value. Getopt::Yath::Option::Map and Getopt::Yath::Option::List support a list of autofill data for setting key/value pairs, or adding items to an array.

These are valid for anything:

autofill => 'foo',
autofill => 123,
autofill => sub { "hi" }

This is valid for an Getopt::Yath::Option::Map:

autofill => sub { return ('foo' => 'bar') }

This is valid for an Getopt::Yath::Option::List:

autofill => sub { return (1, 2, 3, 4) }
  • normalize => sub { my ($input) = @_; ...; return $output } β€” if you wanna normalize or transform a value, this hook is your girl. The sub gets the option and the input value as its arguments. You should return the new value to set, or just return the input value if it doesn't need to change. πŸͺ„
  • trigger => sub { my ($opt, %params) = @_; ... } β€” this gets called any time the option is parsed from the command line, or whenever the command line clears the option.
NOTE: it will not run when initial, autofill, or default values are set.

The %params passed into the sub look like this:

(
    # If this trigger is called because the value is cleared via --no-OPT:
    action => 'clear',
    val    => undef,

    # If a value is set because of --opt being parsed:
    action   => 'set',
    val      => [...],
    ref      => $ref,
    state    => $state,
    options  => $self,
    settings => $settings,
    group    => $group,
);

Note that val is always passed in as an arrayref. For simple scalar type options this will only ever have 1 value. For list or map types it may have multiple values, and also note that for such types the trigger will only see the newly added values in the 'val' arrayref, not the values already included β€” which is important, because list and map types can be built over several assignments.

  • from_env_vars => \@LIST β€” a list of environment variables that will be used to populate the option's initial value. These get checked in order, and the first one that is set is the one that will be used β€” the others won't be checked once a value is found. This will prevent the default value from being used, but using the option on the command line will override it. 🌱
Note: an environment variable can be prefixed with a "!" to indicate the value should be boolean-inverted. This means an option like quiet can have from_env_vars => ['!VERBOSE'] to be set to true when the VERBOSE env var is false. This also works when setting a variable, so you could have set_env_vars => ['!VERBOSE'].
  • clear_env_vars => \@LIST β€” a list of environment variables to clear after the options are all populated. This is useful if you wanna use an env var to set an option, but want to make sure no child processes see the environment variable. 🫧
  • set_env_vars => \@LIST β€” bestie, this is a list of environment variables that will be set to the value of this option (if it is set) when argument processing is complete. πŸ’–
⚠️ Note: This is only supported in types that have a single value, maps and lists are not supported.
✨ Note: that an environment variable can be prefixed with a ! to indicate the value should be boolean-inverted. This means that an option like quiet can have from_env_vars => ['!VERBOSE'] to be set to true when the VERBOSE env var is false. This also works when setting a variable, so you could have set_env_vars => ['!VERBOSE'].
  • short_examples => \@LIST, short_examples => ['', 'ARG', '=ARG'], short_examples => [' ARG', '=ARG'] β€” override the default list of arguments when generating docs. This is used for the short form (single dash followed by a single letter and then a value -Ilib, -I lib, -I=lib, -v, -vv, -vvv...) documentation. πŸŽ€
  • long_examples => \@LIST, long_examples => ['', '=ARG'], long_examples => [' ARG', '=ARG'] β€” override the default list of arguments when generating docs. This is used for the long form (double-dash and option name and then a value --include, --include=lib, --include lib) documentation. ✨

🌸 SOURCE 🌸

The source code repository for Getopt-Yath can be found at <http://github.com/Test-More/Getopt-Yath/>. Go give it a star, iykyk. ⭐

πŸ‘‘ MAINTAINERS πŸ‘‘

Chad Granum <exodist@cpan.org>

πŸ’– AUTHORS πŸ’–

Chad Granum <exodist@cpan.org>

Copyright Chad Granum <exodist7@gmail.com>.

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

See <http://dev.perl.org/licenses/>


And that's the whole vibe for Getopt::Yath(3pm) β€” from perl v5.40.1, dated 2026-05-10. Stay iconic, bestie. πŸ’…βœ¨

πŸ“¦ where this page comes from