NAME

Opt - parsing of command line options, and more...


SYNOPSIS

    use Opt qw($OPT);
    Opt::getoptions(["-x","Help string for x",\$x],
                    ["-yINT"],
                    ["--zvalue=STRING"], 
                    ["--mobile",\%StuckInsideOf]
                   );

and then the values associated with those options will be assigned to variables $x, $OPT{y}, $OPT{zvalue}, and $StuckInsideOf{mobile}.


DESCRIPTION

The Opt module is a library whose purpose is to simplify the task of parsing command line arguments to set parameter values for a Perl routine. Opt also gets parameter values from environment variables, option files, and a builtin rudimentary interactive menu. It is much like the standard Getopt modules, but there are a few more bells and whistles. It is mostly meant to be a clone of the similarly named opt for C programs (in fact, this version of Opt.pm was probably distributed with the larger C library).

Opt supports simultaneous use of traditional, bundled, and long (aka POSIX) options

-x
turns on the 'x' feature of your code; in this traditional specification, the option specifier 'x' is only permitted to be one character, usually alphabetic of either case, but Opt.pm also permits other characters, such as the digits 0-9, so you can specify '-2' to indicate that you want a two-sided statistical test. Most punctuation would not be permitted.

-x -y
turns on the 'x' and 'y' features

-xy
turns on both 'x' and 'y' features; putting both options together like this is called ``bundling''.

-z 3.14159,
specifies that the number associated with 'z' should have value 3.14159.

-z3.14159
does the same thing, even though there is no space between the 'x' and '3.14159'; that space is optional.

--xflag
turns on the flag associated with ``xflag''; note the two hyphens and that ``xflag'' is not constrained to be a single character.

--zvalue 3.14159, --zvalue=3.14159
are both permitted, but ``--zvalue3.14159'' is not allowed.

as well as some extra bells and whistles specific to Opt.

@file.opt
specifies that options are read from a file named ``file.opt''.

%file.opt
tells the program to write all the current values of all the options to a file called file.opt. If you want a ``file.opt'' template as a starting point which you might then edit by hand, you can always get one by typing program %file.opt .; using a period ('.') as an argument causes the program to exit gracefully.

Aside: Hmmm, this could be a problem for a program in which '.' might be a reasonable argument, eg a program that was expecting a directory name. Perhaps, we should instead use something like '---exit' instead?

--help
is a special flag which, if it is the first in a command line, tells the program to write a help message and exit. The message is of a ``standard'' format (standard to 'opt' that is) which can be parsed by other programs, such as 'tkopt' which instantly turns any opt-enabled program to be GUI too.

--usage
is a special flag, like --help. if it is the first in a command line, tells the program to write a short usage message and exit.

--menu
pops you into an interactive menu which allows you to see what parameters are available, what they do, and what their current values are. you can then reset those parameters to what you want and run the program.


Functions

getoptions(['--var=TYPE','Help string',\$var], ['-x'], ... )
In principle, getoptions is the only function you need to know about in order to use the Opt package. Each argument ``registers'' a single option, which essentially sets up a table that associates each option with attributes specifying what kind of option it is, and which variable in the Perl script it corresponds to. After all the options are registered, the @ARGV array is parsed, and the variables are all set accordingly. This is the one-function-does-all invocation; you may prefer to call its individual components: for instance, the example in the SYNOPSIS is equivalent to:

    Opt::register('-x','Help string for x',\$x);
    Opt::register('-yINT');
    Opt::register('--zvalue=STRING');
    Opt::register('--longvar',\%LocalHashOfOptions);
    @ARGV=Opt::opt($0,@ARGV);

The longer form is a little closer to what the interface would look like in the C version of opt. You may prefer this form if, say, you want to perform argument processing on an array other than @ARGV.

register('--var=TYPE','Help string',\$var)
This function registers a single option of type TYPE, named 'var', and associates it with the variable $var. Invocations of --var=value on the command line will lead to setting $var='value' in the Perl script. The help string is optional, as is the $var reference. If the variable reference is not specified, then a variable $OPT{var} is created, and it is associated with the option. TYPE is one of: NUL, INT, UNSINT, SHORT, LONG, CHAR, INTLEVEL, FLOAT, DOUBLE, FLAG, NEGFLAG, ABSFLAG, ABSNEGFLAG, STRING, or UNDELIM.

optreg(\$var,"TYPE",'v',"Help string")
This is another version of the register function. It is arguably not as intuitive as register, but it more closely matches the way that options are registered in the C version of opt. This is not the most convenient way to register a function, but it mimics the C opt version. This form only registers one-character option names. Alternative forms include:

optrega(\$var,"TYPE",'v',"var","Help string")
Provides two names for the variable $var, a long name (``var'') and a short name ('v'). As an implementation issue, all other registration functions, including the ones below as well as register and even getoptions, all call optrega to actually register the option.

optregc(\$var,"TYPE",'v')
only provides a short single-character name ('v') for the variable $var.

Each of these functions also has a form optreg_TYPE(\$var,'v',"Help string"), in which the TYPE is not a string argument but is part of the function name.

@argvnew=opt($0,@argv)
After all the options are registered, the function opt does the actual parsing of command line as given in the array @argv. Here $0 is the name of the program. Note that opt does ``nondestructive'' argument processing; so the argument @argv is unaltered by the call to opt. The result @argvnew is the list of arguments that are unprocessed by opt. In typical usage, you would write @ARGV=Opt::opt($0,@ARGV);

Hooks

Hooks are functions which are written by the Perl application programmer (but not by the Opt developer), which Opt calls at certain points in its processing. Among them are:

useUsageLines("Usage: \%s [options]")
specifies the first line(s) of the usage message. The '\%s' will be expanded out as the program name. Multiple lines can be providee as separate arguments. =item useMainFcn(\&MyMain);

specifies that the function &MyMain will be run whenever the ``='' is invoked on the opt menu.

useEnvString('ENVAR');
specifies that the environment variable can be used to specify default options. eg, if ENVAR='-x+ -y-', then the default value for 'x' will be TRUE, and for 'y' will be FALSE.

useHash(\%OPTION);
specifies that options registered without an explicitly associated reference will be associated with the hash %OPTION. That is,

    %OPTION=();
    useHash(\%OPTION);
    Opt::register("-x");

will associate the option -x with the variable $OPTION{x}. By default, the package does an equivalent of useHash(\%OPT), unless that is changed by this function or by the useScalarPrefix function.

useScalarPrefix('opt_');
specifies that options registered without an explicitly associated reference will be associated with the scalar string $opt_xxx, where xxx is the name of the option.

noScalarPrefix('opt_');
disables scalar prefix for options.

useInitFile('/etc/progrc')
still not implemented; equivalent to @/etc/progrc as the first argument in the command line. Useful for site-wide configurations.

IMPLEMENTATION DETAILS

The Option Classes

An Option is an object which contains information about an individual option (name, help string, variable they refer to, and type), as well as methods for manipulating it, eg reading its value from a string, writing its value to strings appropriate for menus, optfiles, etc.

Option::Base is the base option class; it is an actual working class (not an ``abstract class'' in the sense of C++), and is actually used for string options, but most of the other classes are derived from it.

The derived classes are for different kinds of options; currently these options are:

   Option::Base       NUL? STRING UNDELIM CSTRING UNDELIMC
   Option::Numeric    FLOAT DOUBLE
   Option::Int        INT SHORT LONG
   Option::UInt       UINT USHORT ULONG
   Option::IntLevel   INTLEVEL
   Option::Flag       FLAG NEGFLAG ABSFLAG ABSNEGFLAG

Each object contains (among other things) a reference to a scalar variable. Getting and setting the value of this variable is the whole point of the Opt package. Since the "variable associated with the given class object" is a cumbersome phrase, I will refer to that variable as the optvar

Methods

The methods defined in these classes are:

default()
returns a ``default value'' for the class; it is the empty string for STRING classes, and zero for numeric classes.

getval()
returns the value of the variable associated with the given class object; ie, the value of the optvar.

setval(var)
sets the optvar to the value of the variable in the argument. (Should I call that the argvar?) Generally, setval() is implemented with a call to fixval(), so that it sets the optvar to a valid value.

fixval(var)
does not affect the optvar at all. It converts the argument value to a value that is consistent with the argument type, and returns the consistent value. eg, if the option is a UINT (unsigned integer), then with an argument of -33.5, fixval will return 33.

valOf(string)
does not affect the optvar. It parses the input argument, usually thought of as a string (but this is Perl, so it can in practice be just about anything), and returns a value

For many data types, valOf() is an identity function, returning the same value that was provided as an argument. But for some types, it does a little massaging. For example, if the option is a FLAG type, then valOf("+") will return a 1; if the option is a NEGFLAG, then valOf("+") will return a 0.

If the function valOf() is called without an argument, then it sets optvar as if the option had been invoked without an argument. For example, if you want -f to turn on a flag $f, then setvalOf() will toggle the value of the flag variable $f.

setvalOf(string)
is equivalent to setval(valOf(string)); that is, it sets the optvar according to the argument string.

requiresArg()
returns 0 or 1 according to whether the option requires an argument; eg, an integer option requires an argument because you use -n15 or -n 15 to set the value to 15, the lone string -n makes no sense. For a flag option, by contrast, a lone -f on the command line is all that is needed to toggle the flag.

toString()
returns a string representation of the value of optvar that is appropriate for writing to a file (that can then be read by programs using Opt). For example, if the option is a FLAG type, and it has a value of 1, then toString() will return ``+''.

toMenu()
is much like toString(), except that it returns a stringified optvar that is appropriate for the builtin menu.

toMenuLine()
writes out the whole line that appears in the interactive menu; it is standardized formatting with a call to toMenu() to get the value of the optvar.

toFileLine()
is similar to toMenuLine(), except that it writes a line appropriate for the full line of an .opt file. Thus it includes the name of the option, its toString()ified value, and a commented-out help string.

Thanks to the magic of inheritance, we do not have to define every one of these functions for every data type. The table below shows how for which classes the different functions need to be defined. An x indicates an implementation of that function for that class, while ... indicates that the function is inherited.

                       Inheritance Table
                       -----------------
  Function    Class: B   N   I   U   L   F
  default            x   x................
  getval             x....................
  setval             x....................
  fixval             x   x   x   x....   x
  valOf              x............   x   x 
  setvalOf           x....................
  requiresArg        x............   x....
  toString           x............   x   x
  toMenu             x............   x   x
  toMenuLine         x....................
  toFileLine         x....................

The classes (which are columns in this table) are: B=Base, N=Numeric, I=Integer, U=UnsignedInt, L=IntLevel, and F=Flag. The inheritance hierarchy is essentially linear, with each class being derived from the class to its left in the above table. Conceptually, the hierarchy is shown below, except that there is no S=String class (we just use the B=Base class, and check if $$self{type} =~ /STRING|UNDELIM/ for the few occasions where strings behave differently from the base.

     +- S
     |
  B -+- N --- I --- U --- L --- F               

hasname()
returns 1 if the option has a short (one-character) name that can be invoked from the command line preceeded by a single dash (eg, -x).

haslongname()
returns 1 if the option has a long (typically multi-character) name that can be invoked from the command line preceeded by a double dash (eg, --xcaliber).

thename()
returns the short name if it exists; if there is no short name, then this function returns the long name. if there is neither a short nor a long name, the function returns 'undef'.

Bugs

Copyright

Copyright (C) 1998, James Theiler; email: jt@lanl.gov

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details.

You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.