The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Getopt::OO - Perl object oriented version of Getopt that uses a template to describe command line arguments and handles most common command line parsing.

SYNOPSIS

 use Getopt::OO qw(Debug Verbose);

 my ($handle, @errors) = Getopt::OO->new(\@ARGV,
    -d => {
        help => 'turn on debug output',
        callback => sub {Debug(1); 0},
    },
    -o => {
        help => 'another arg.',
    },
    -f => {
        help => 'arg that expects one more arg.',
        n_values => 1,
    },
    --long {
        help => 'long option'
    },
 );
  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 argment.\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 parses this using a hash as its template.

We expect three types of arguments on the command line: arguments that start with a single dash, those that start with 2 dashes and arguments for these dashed arguments.

Input arguments that start with a single dash can be combined: i.e. "tar -xvf file" is the same as "tar -x -v -f file".

Input arguments that start with 2 dashes are literal -- they will be used exactly as found.

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

Valid values for each dashed argument are:

help

A help string associated with the argument.

n_values

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

multiple

If this exists, it means the argument 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.

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, $arg_list) = @_
        ...

the caller could get help with $handle->Help() or its values with $handle->Values($option). He could also manipulate the argument list.

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', and the v and f options both expected one additional value, the argument list would have only the '3' left and $handle->Values($option) would return 2.

If the callback returns a non-zero value, it failed. If this is a string (i.e. non-int) we add this string to the list of errors. If it is an int and die is enabled, we will exit with the value returned.

Template non-dashed arguments

Only four non-dashed keys are allowed: 'required' and 'usage' and 'die' 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]'.

die

By default, behaviour is to check for errors and if any are encountered, print usage, an error and die. To return even if errors are encountered, set die => 0.

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. 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',
                }

Methods associated with the OO module:

my($handle, @errors) = new(\@ARGV, %Template)

Creator function. Expects a reference to the argument list and a template that explanes how to parse the input arguments. Returns an object reference and a list of errors. We also have a Errors method later that can be used to retrieve any errors if you prefer accessing the errors and the object handle separately.

$handle->Values(argument);

Values() returns the number of command line options that were matched.

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

ClientData();

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.

Example

AUTHOR

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

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.