Getopt::Flex - Option parsing, done different.
version 1.07
use Getopt::Flex; my $foo; my $use; my $num; my %has; my @arr; my $cfg = { 'non_option_mode' => 'STOP', }; my $spec = { 'foo|f' => {'var' => \$foo, 'type' => 'Str'}, 'use|u' => {'var' => \$use, 'type' => 'Bool'}, 'num|n' => {'var' => \$num, 'type' => 'Num'}, 'has|h' => {'var' => \%has, 'type' => 'HashRef[Int]'}, 'arr|a' => {'var' => \@arr, 'type' => 'ArrayRef[Str]'} }; my $op = Getopt::Flex->new({spec => $spec, config => $cfg}); if(!$op->getopts()) { print "**ERROR**: ", $op->get_error(); print $op->get_help(); exit(1); }
Getopt::Flex makes defining and documenting command line options in your program easy. It has a consistent object-oriented interface. Creating an option specification is declarative and configuration is optional and defaults to a few, smart parameters. Generally, it adheres to the POSIX syntax with GNU extensions for command line options. As a result, options may be longer than a single letter, and may begin with "--". Support also exists for bundling of command line options and using switches without regard to their case, but these are not enabled by defualt.
Getopt::Flex is an alternative to other modules in the Getopt:: namespace, including the much used Getopt::Long and Getopt::Long::Descriptive. Other options include App::Cmd and MooseX::Getopt (which actually sit on top of Getopt::Long::Descriptive). If you don't like this solution, try one of those.
Getopt::Flex supports long and single character options. Any character from [a-zA-Z0-9_?-] may be used when specifying an option. Options must not end in -, nor may they contain two consecutive dashes.
To use Getopt::Flex in your Perl program, it must contain the following line:
use Getopt::Flex;
In the default configuration, bundling is not enabled, long options must start with "--" and non-options may be placed between options.
Then, create a configuration, if necassary, like so:
my $cfg = { 'non_option_mode' => 'STOP' };
For more information about configuration, see "Configuring Getopt::Flex". Then, create a specification, like so:
my $spec = { 'foo|f' => {'var' => \$foo, 'type' => 'Str'}, };
For more information about specifications, see "Specifying Options to Getopt::Flex". Create a new Getopt::Flex object:
my $op = Getopt::Flex->new({spec => $spec, config => $cfg});
And finally invoke the option processor with:
$op->getopts();
Getopt::Flex automatically uses the global @ARGV array for options. If you would like to supply your own, you may use set_args(), like this:
set_args()
$op->set_args(\@args);
In the event of an error, getopts() will return false, and set an error message which can be retrieved via get_error().
getopts()
get_error()
Getopt::Flex also stores information about valid options, invalid options and extra options. Valid options are those which Getopt::Flex recognized as valid, and invalid are those that were not. Anything that is not an option can be found in extra options. These values can be retrieved via:
my @va = $op->get_valid_args(); my @ia = $op->get_invalid_args(); my @ea = $op->get_extra_args();
Getopt::Flex may also be used to provide an automatically formatted help message. By setting the appropriate desc when specifying an option, and by setting usage and desc in the configuration, a full help message can be provided, and is available via:
my $help = $op->get_help();
Usage and description are also available, via:
my $usage = $op->get_usage(); my $desc = $op->get_desc();
An automatically generated help message would look like this:
Usage: foo [OPTIONS...] [FILES...] Use this to manage your foo files Options: --alpha, --beta, Pass any greek letters to this argument --delta, --eta, --gamma -b, --bar When set, indicates to use bar -f, --foo Expects a string naming the foo
Options are specified by way of a hash whose keys define valid option forms and whose values are hashes which contain information about the options. For instance,
my $spec = { 'file|f' => { 'var' => \$file, 'type' => 'Str' } };
Defines a switch called file with an alias f which will set variable $var with a value when encountered during processing. type specifies the type that the input must conform to. Only type is required when specifying an option. If no var is supplied, you may still access that switch through the get_switch method. It is recommended that you do provide a var, however. For more information about get_switch see get_switch. In general, options must conform to the following:
$var
get_switch
$_ =~ m/^[a-zA-Z0-9|_?-]+$/ && $_ =~ m/^[a-zA-Z_?]/ && $_ !~ m/\|\|/ && $_ !~ /--/ && $_ !~ /-$/
Which (in plain english) means that you can use any letter A through Z, upper- or lower-case, any number, underscores, dashes, and question marks. The pipe symbol is used to separate the various aliases for the switch, and must not appear together (which would produce an empty switch). No switch may contain two consecutive dashes, and must not end with a dash. A switch must also begin with A through Z, upper- or lower-case, an underscore, or a question mark.
The following is an example of all possible arguments to an option specification:
my $spec = { 'file|f' => { 'var' => \$file, 'type' => 'Str', 'desc' => 'The file to process', 'required' => 1, 'validator' => sub { $_[0] =~ /\.txt$/ }, 'callback' => sub { print "File found\n" }, 'default' => 'input.txt', } };
Additional specifications may be added by calling add_spec. This allows one to dynamically build up a set of valid options.
add_spec
When specifying a var, you must provide a reference to the variable, and not the variable itself. So \$file is ok, while $file is not. You may also pass in an array reference or a hash reference, please see "Specifying a type" for more information.
\$file
$file
Specifying a var is optional, as discussed above.
A valid type is any type that is "simple" or an ArrayRef or HashRef parameterized with a simple type. A simple type is one that is a subtype of Bool, Str, Num, or Int.
Bool
Str
Num
Int
Commonly used types would be the following:
Bool Str Num Int ArrayRef[Str] ArrayRef[Num] ArrayRef[Int] HashRef[Str] HashRef[Num] HashRef[Int] Inc
The type Inc is an incremental type (actually simply an alias for Moose's Int type), whose value will be increased by one each time its appropriate switch is encountered on the command line. When using an ArrayRef type, the supplied var must be an array reference, like \@arr and NOT @arr. Likewise, when using a HashRef type, the supplied var must be a hash reference, e.g. \%hash and NOT %hash.
Inc
ArrayRef
\@arr
@arr
HashRef
\%hash
%hash
You can define your own types as well. For this, you will need to import Moose and Moose::Util::TypeConstraints, like so:
Moose
Moose::Util::TypeConstraints
use Moose; use Moose::Util::TypeConstraints;
Then, simply use subtype to create a subtype of your liking:
subtype
subtype 'Natural' => as 'Int' => where { $_ > 0 };
This will automatically register the type for you and make it visible to Getopt::Flex. As noted above, those types must be a subtype of Bool, Str, Num, or Int. Any other types will cause Getopt::Flex to signal an error. You may use these subtypes that you define as parameters for the ArrayRef or Hashref parameterizable types, like so:
my $sp = { 'foo|f' => { 'var' => \@arr, 'type' => 'ArrayRef[Natural]' } };
or
my $sp = { 'foo|f' => { 'var' => \%has, 'type' => 'HashRef[Natural]' } };
For more information about types and defining your own types, see Moose::Manual::Types.
Specifying a type is required.
desc is used to provide a description for an option. It can be used to provide an autogenerated help message for that switch. If left empty, no information about that switch will be displayed in the help output. See "Getting started with Getopt::Flex" for more information.
Specifying a desc is optional, and defaults to ''.
Setting required to a true value will cause it make that value required during option processing, and if it is not found will cause an error condition.
Specifying required is not required, and defaults to 0.
A validator is a function that takes a single argument and returns a boolean value. Getopt::Flex will call the validator function when the option is encountered on the command line and pass to it the value it finds. If the value does not pass the supplied validation check, an error condition is caused.
Specifying a validator is not required.
A callback is a function that takes a single argument which Getopt::Flex will then call when the option is encountered on the command line, passing to it the value it finds.
Specifying a callback is not required.
defaults come in two flavors, raw values and subroutine references. For instance, one may specify a string as a default value, or a subroutine which returns a string:
'default' => 'some string'
'default' => sub { return "\n" }
When specifying a default for an array or hash, it is necessary to use a subroutine to return the reference like,
'default' => sub { {} }
'default' => sub { [] }
This is due to the way Perl handles such syntax. Additionally, defaults must be valid in relation to the specified type and any specified validator function. If not, an error condition is signalled.
Specifying a default is not required.
Configuration of Getopt::Flex is very simple. Such a configuration is specified by a hash whose keys are the names of configuration option, and whose values indicate the configuration. Below is a configuration with all possible options:
my $cfg = { 'non_option_mode' => 'STOP', 'bundling' => 0, 'long_option_mode' => 'SINGLE_OR_DOUBLE', 'case_mode' => 'INSENSITIVE', 'usage' => 'foo [OPTIONS...] [FILES...]', 'desc' => 'Use foo to manage your foo archives', 'auto_help' => 1, };
What follows is a discussion of each option.
non_option_mode tells the parser what to do when it encounters anything which is not a valid option to the program. Possible values are as follows:
STOP IGNORE SWITCH_RET_0 VALUE_RET_0 STOP_RET_0
STOP indicates that upon encountering something that isn't an option, stop processing immediately. IGNORE is the opposite, ignoring everything that isn't an option. The values ending in _RET_0 indicate that the program should return immediately (with value 0 for false) to indicate that there was a processing error. SWITCH_RET_0 means that false should be returned in the event an illegal switch is encountered. VALUE_RET_0 means that upon encountering a value, the program should return immediately with false. This would be useful if your program expects no other input other than option switches. STOP_RET_0 means that if an illegal switch or any value is encountered that false should be returned immediately.
STOP
IGNORE
_RET_0
SWITCH_RET_0
VALUE_RET_0
STOP_RET_0
The default value is IGNORE.
bundling is a boolean indicating whether or not bundled switches may be used. A bundled switch is something of the form:
-laR
Where equivalent unbundled representation is:
-l -a -R
By turning bundling on, long_option_mode will automatically be set to REQUIRE_DOUBLE_DASH.
REQUIRE_DOUBLE_DASH
Warning: If you pass an illegal switch into a bundle, it may happen that the entire bundle is treated as invalid, or at least several of its switches. For this reason, it is recommended that you set non_option_mode to SWITCH_RET_0 when bundling is turned on. See "Configuring non_option_mode" for more information.
The default value is 0.
0
This indicates what long options should look like. It may assume the following values:
REQUIRE_DOUBLE_DASH SINGLE_OR_DOUBLE
REQUIRE_DOUBLE_DASH is the default. Therefore, by default, options that look like:
--verbose
Will be treated as valid, and:
-verbose
Will be treated as invalid. Setting long_option_mode to SINGLE_OR_DOUBLE would make the second example valid as well. Attempting to set bundling to 1 and long_option_mode to SINGLE_OR_DOUBLE will signal an error.
SINGLE_OR_DOUBLE
1
The default value is REQUIRE_DOUBLE_DASH.
case_mode allows you to specify whether or not options are allowed to be entered in any case. The following values are valid:
SENSITIVE INSENSITIVE
If you set case_mode to INSENSITIVE, then switches will be matched without regard to case. For instance, --foo, --FOO, --FoO, etc. all represent the same switch when case insensitive matching is turned on.
INSENSITIVE
--foo
--FOO
--FoO
The default value is SENSITIVE.
SENSITIVE
usage may be set with a string indicating appropriate usage of the program. It will be used to provide help automatically.
The default value is the empty string.
desc may be set with a string describing the program. It will be used when providing help automatically.
auto_help can be set to true to enable the automatic creation of a help|h switch, which, when detected, will cause the help to be printed and exit(0) to be called. Additionally, if the given switches are illegal (according to your configuration and spec), the error will be printed, the help will be printed, and exit(1) will be called.
help|h
Use of auto_help also means you may not define other switches help or h.
help
h
The default value is false.
Invoking this method will cause the module to parse its current arguments array, and apply any values found to the appropriate matched references provided.
Add an additional spec to the current spec.
Set the array of args to be parsed. Expects an array reference.
Get the array of args to be parsed.
After parsing, this returns the number of valid switches passed to the script.
After parsing, this returns the valid arguments passed to the script.
After parsing, this returns the number of invalid switches passed to the script.
After parsing, this returns the invalid arguments passed to the script.
After parsing, this returns anything that wasn't matched to a switch, or that was not a switch at all.
After parsing, this returns the extra parameter passed to the script.
Returns the supplied usage message, or a single newline if none given.
Returns an automatically generated help message
Returns the supplied description, or a single newline if none provided.
Returns an error message if set, empty string otherwise.
Passing this function the name of a switch (or the switch spec) will cause it to return the value of a ScalarRef, a HashRef, or an ArrayRef (based on the type given), or undef if the given switch does not correspond to any defined switch.
The source code repository for this project is located at:
http://github.com/f0rk/getopt-flex
Ryan P. Kelly <rpkelly@cpan.org>
This software is Copyright (c) 2011 by Ryan P. Kelly.
This is free software, licensed under:
The MIT (X11) License
To install Getopt::Flex, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Getopt::Flex
CPAN shell
perl -MCPAN -e shell install Getopt::Flex
For more information on module installation, please visit the detailed CPAN module installation guide.