NAME

Getopt::OO - An object oriented command line parser. It handles short, long and multi (--x ... -) value options. It also incorporates help for options to simplify generation of usage statements.

SYNOPSIS

 use Getopt::OO qw(Debug Verbose);

 my ($handle) = Getopt::OO->new(\@ARGV,
    '-d' => {
        help => 'turn on debug output',
        callback => sub {Debug(1); 0},
    },
    '-o' => {
        help => 'another option.',
    },
    '-f' => {
        help => 'option that expects one more value.',
        n_values => 1,
    },
    '--long' {
        help => 'long option'
    },
    '--multiple_' => {
        help =>  [
            "Everything between '--multiple_values' and '-' is",
            "an value for this options",
        ],
        'multi_value' => 1,
        'multiple= => 1, # Can happen more than once on command line.
    },
    other_values => {
		help => 'file_1 ... file_n',
		multi_value => 1,
	},
 );
  if ($handle->Values()) {
    Debug("You will get output if -d was on command line");
    if (my $f = handle->Values(-f)) {
        print "Got $f with the -f value.\n";
    }
  }
  else {
    print "No options found on command line.\n";
 }

DESCRIPTION

Getopt::OO is an object oriented tool for parsing command line arguments. It expects a reference to the input arguments and uses a perl hash to describe how the command line arguments should be parsed. Note that by parsed, we mean what options expect values, etc. We check to make sure values exist on the command line as necessary -- nothing else. The caller is responsible for making sure that a value that he knows should be a file exists, is writable, or whatever.

Command line arguments can be broken into two distinct types: options and values that are associated with these options. In windows, options often start with a '/' but sometimes with a '-', but in unix they almost universally start with a '-'. For this module options start with a '-'. We support two types of options: the short single dashed options and the long double dashed options. The difference between these two is that with this module the short options can be combined into a single option, but the long options can not. For example, most of us will be familiar with the tar -xvf file command which can also be expressed as -x -v -f file. Long options can not be combined this way, so '--help' for example must always stand by itself.

The input template expects the option names as its keys. For instance if you were expecting -xv --hello as possible command line options, the keys for your template hash would be -x, -v, and --hello.

Valid values for each dashed options are:

help

A help string associated with the options.

n_values

Number of values the option expects. Any value greater than or equal to 0 is valid with 0 being the default.

multiple

If this exists, it means the option may be encountered multiple times. For example --

'-a' => {
    n_values => 3,
    multiple => 1,
 },

says that if -a is encountered on the command line, the next three arguments on the command line are associated with it and that it may be encountered multiple times.

multi_value

Use this if you know that the option expects multiple values, but you don't know how many till the user executes the script. This tag is only valid for long options. Everything between the option and a '-' is considered a value. For example, suppose you wanted to pass in a group of user names, your command line might look like: --users fred joe mary gandalf frodo -

callback

This must be a code reference. If the template entry looked like:

'-a' => {
    n_values => 1,
    multiple => 1,
    callback => \&xyz,
},

then we would call the function xyz with the a Getopt::OO handle and the option found and the argument reference. For instance if the function looked like:

sub Callback {
   my ($handle, $option) = @_
   ...

the caller could get help with $handle->Help() or its values with $handle->Values($option).

Note that the only option information available at this point is what has been found on the command line up to this point. For example, if the callback were associated with the -f option and the command line looked like -xvfz 1 2 3, we haven't yet parsed the -z option, so no information associated with this option is available.

If the callback returns a non-0 value, it failed. We execute 'die $string' where $string is the returned value.

Template non-dashed arguments

Only four non-dashed keys are allowed: 'usage', 'other_values', 'required', and 'mutual_exclusive'.

usage

This is a string. Typically it wil be the first part of a help statement and combined with the 'help' arguments for the various dashed arguments in the template, creates the complete usage message. By default, we will create a usage string that is the base name of the executable ($0) and just the string '[options]'.

other_values

Usually all the argments on a command line aren't associated with options. For instance, a function may always require a file name but have several other options too. It's signature might look like

script [-v] input_file

other_values allows you to supply help for the usage message and tell the parser how many args to expect. Use might look like

other_values => {
       help => 'file_1 ... file_n',
},

For the call to script above, the first output line of the usage statement would look like:

script [-v] file_1 ... file_n

and since multi_value is set, an error would occur unless at least one value were passed in.

Use multi_value or n_values to tell the parser how many values to expect. Both of these values are optional and if not supplied, the parser doesn't check for values after the parsing is done.

help is also optional. If it is not supplied, we use n_values or multi_value to print a message that makes sense. Note that if n_values or multi_value are set, it is an error to not have other values after the options are parsed, but you can just supply the help value and no other checking of the other_values will occur.

As discussed below, other_values will also accept a callback and use ClientData and return its values using $handle->Values('other_values'). Unlike the other options, other_values can not be 'multiple'.

By default, any values not used by other arguments will get assigned to the 'other_values' option. This is done mostly to allow error checking. One of the decisions early in programming this module was that I wanted to allow parsed arguments to start with a '-'. Thus, something like

--args => {'n_values' => 3},

would allow a command line like '--args -a 1 5' and $h->Values('--args') would return a 3 element array consisting of -a, 1, and 5. Unfortunatly this makes both parsing and checking of command line arguments more difficult. For example, if you had something like

-a => {'n_values' => 2},

and your command line looks like '-a 1 2 3 -s', the values after 3 don't get parsed and are left on the argument list.

To simplify checking this situation, two changes were made in version 0.07 of this module: 1) you can now set the 'other_values' 'n_values' option to 0 and we will die if any unparsed command line values exist, or 2) unparsed command line values are now placed on the 'other_values' option so you can use $h->Values('other_values') to examine the un-parsed arguments.

required

This is an array reference to required arguments. It is an error if none of these are found on the command line.

mutual_exclusive

This is an list reference. It says "it is an error to receive these arguments at the same time." For example, "tar cx" would not make sense because you can't both create and extract at the same time. Give a reference for each set of mutually exclusive arguments. In the trivial case where you only have one set, the argument can be just a reference to a list, but in the more complicated case where you have sets of mutually exclusive arguments, this will be a refrence to an list of list references. The template to express this might look like:

mutual_exclusive => [ qw( -x -c ) ],
-x => {
    help => 'Extract a tar file',
},
-c => {
    help => 'Create a tar file',
}

As stated above, this would also be correct.

mutual_exclusive => [ 
    [qw( -x -c )],
],
-x => {
    help => 'Extract a tar file',
},
-c => {
    help => 'Create a tar file',
}

Methods associated with the OO module:

my $handle = Getopt::OO->new(\@ARGV, %Template)

Creator function. Expects a reference to the argument list and a template that explanes how to parse the input arguments and returns an object reference. If you want to catch parse errors rather than having the parser print an error message and exit, do this:

my $handle = eval {Getopt::OO>new(\@ARGV, %template)};
if ($@) {...

$@ will contain your error string if one exists and be empty otherwise.

$handle->Values(argument);

Values() returns a list of command line options that were matched in the order they were found. In scalar context, this is the number of matches.

Values($option) depends on the 'n_values' and the 'multiple' for the option in the template. If the option had no n_values element or n_values was 0, Values(option) will return 0 if the option was not found on the command line and 1 if it was found. If n_values was set to 1 and multiple was not set or was set to 0, we return nothing if the argument was not found and the value of the argument if one was found. If n_values > 1 and multiple was not set or if n_values is 1 and multiple was set, we return a list containing the values if the values were found and nothing otherwise. If the of n_values is greater than 1 and multiple is set, we retrun a list of list references -- each contining n_values elements, or nothing if no matches were found.

The example below shows a template and accesing the values returned by the parser. The template is ordered from the simplest use to the most complex.

Given the command line arguments:

-abcde b c0 d0 d1 e0 e1 -c c1 -e e2 es

and the following to create our GetOpt handle:

use Getopt::OO qw(Debug);
my @argv = qw (-abcde b c0 d0 d1 e0 e1 -c c1 -e e2 es);
my $h = Getopt::OO->new(\@argv,
   '-a' => {},
   '-b' => { n_values => 1, },
   '-c' => { n_values => 1, multiple => 1, },
   '-d' => { n_values => 2, },
   '-e' => { n_values => 2, multiple => 1, },
);
my $n_options = $h->Values();
my $a = $h->Values('-a');
my $b = $h->Values('-b');
my @c = $h->Values('-c');
my @d = $h->Values('-d');
my @e = $h->Values('-e');

Example 1.  ValuesDemo.pl

my $help_string = $handle->Help();

Get the string string we built for this template. Note that this can be used to check the template to make sure it is doing what you expect. It will contain optional arguments separated from non optional, indicates required and mutually exclusive options and indicates which options expect values and how many values.

my $client_data = $handle->ClientData($option);

The ClientData method is supplied to allow data to be associated with an option. The data must be scalar or a reference. All calls to this method return what ever the data was replied to, but it is only set if data is passed in.

To set the data:

$h->ClientData($option, $x);

To get the data:

$x = $h->ClientData($option);

Debug and Verbose Functions

We also supply two functions the user can export. These are the Debug and the Verbose functions. If the functions are exported and we find --debug or --verbose in the command line arguments, the associated function is enabled. These two functions behave in multiplt ways: If called with just a '0' or '1', the function is disabled or disabled. If called with no arguments, we return the state of the function: 0 if disabled and 1 if enabled. If called with a list and the first element of the list looks like a printf format statement, we behave like printf, and otherwise we behave like a simple print statement. If the function is called with a single argument that is a reference to an IO::File object, we will attempt to send all further output to this handle. Note that the object must be enabled before any output will occur though.

EXPORT

None by default.

SEE ALSO

Several example scripts are included in the release under the directory 'Demo'.

AUTHOR

Steven Smith, <sjs@chaos-tools.com>

COPYRIGHT AND LICENSE

Copyright (C) 2004 by Steven Smith

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.3 or, at your option, any later version of Perl 5 you may have available.