Getopt::Yath(3pm)
β¨ 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 aGetopt::Yath::Instanceobject. 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 aGetopt::Yath::Stateobject. if there's a problem parsing, like invalid options in the array, exceptions get thrown. so like, be careful bestie. seeGetopt::Yath::Statefor 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->stopwith 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->stopwith the remaining arguments available via$parsed->remains.no_set_env => BOOLβ set this to true to prevent any modifications to%ENV.$parsed->envwill contain the environment variable changes that would have been made. note: the env accessor is always populated even if%ENVis modified directly. π
include_options('Options::Module::A', 'Options::Module::B', ...)β lets you build libraries ofGetopt::Yathoptions 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 validGetopt::Yath::Optionsubclass. 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::inGetopt::Yath::Option::TYPE. You can also specifyGetopt::Yath::Option::TYPEorGetopt::Yath::Option::TYPE::SubTypedirectly. However if you need to use a module that is not in theGetopt::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 theGetopt::Yath::Instanceobject and the parse state hashref as arguments.$weightcontrols execution order (lower weights run first, default is0).$applicableis 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 anoption_groupblock, the group'sapplicableis 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 MEis sorted to99999(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 tooption(). it's used to build the default values for bothfieldandname.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 validGetopt::Yath::Optionsubclass, 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 VALor--opt=val. Wanna wipe it?--no-optclears the value. π§ΌBoolβ it's either on or off, simple as.--optturns it on,--no-optturns it off. Default is off unless you pass in adefaultparameter. ποΈCountβ an integer, and the default is to start at0.--optincrements the counter,--no-optresets the counter back to zero, and--opt=VALlets you specify a desired count directly. π’Listβ can take multiple values.--opt VALappends a value to the list.--no-optwill empty the list. And if you give it asplit_onparameter then a single use can set multiple values β like, ifsplit_onis set to,and you pass--opt foo,bar, then bothfooandbarget added to the list. πMapβ expects all values to bekey=valuepairs and produces a hashref. So--opt foo=barwill set$h{foo} = 'bar'. And again, with asplit_onparameter a single use can set multiple values β ifsplit_onis 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--optadds the default value(s) to the list. The--opt=VALform adds additional values.AutoMapβ combo of 'Auto' and 'Map'. The no-arg form--optadds the default key+value pairs to the hash. The--opt=KEY=VALform adds additional values.PathListβ likeList, 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β likePathListbut with autofill support. The no-arg form--optadds the autofill paths, while--opt=pathadds a specific path.BoolMapβ matches several--OPTION-XXXand--no-OPTION-XXXoptions based on a regex pattern, populating a hashref where each matched key gets a true or false value depending on the--no-prefix. Requires apatternattribute. π§©
π 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 placeoption()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 thegroupfield.
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 overrideallows_shortval()to return false to forbid this form β as of right nowGetopt::Yath::Option::BoolandGetopt::Yath::Option::Countdisable this form.)-sssβ so far only theGetopt::Yath::Option::Counttype 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--alt1or--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 is0. 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 thatGetopt::Yath::Option::Mapcan start with an empty hash, andGetopt::Yath::Option::Listcan 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 toinitialize, 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 forGetopt::Yath::Option::Autoand 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 likequietcan havefrom_env_vars => ['!VERBOSE']to be set to true when theVERBOSEenv var is false. This also works when setting a variable, so you could haveset_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 likequietcan havefrom_env_vars => ['!VERBOSE']to be set to true when theVERBOSEenv var is false. This also works when setting a variable, so you could haveset_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 π
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
- ubuntu stonking: libgetopt-yath-perl 2.000011-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms