Programs need input, and for many programs, input begins on the command line. For example, a program to print files might be invoked as
pr -l -n -a 10:00 foo barpr is the name of the program; it is followed here by six arguments. The arguments are of two sorts: options and file names.
$ARGV[0] '-l' $ARGV[1] '-n' $ARGV[2] '-a' $ARGV[3] '10:00' $ARGV[4] 'foo' $ARGV[5] 'bar'Now the fun starts. Given @ARGV as shown, the program has to identify -l, -n, and -a as options, associate '10:00' with -a, and identify foo and bar as file names. This is called parsing the command line.
Getopt::Declare An easy-to-use WYSIWYG command-line parser Getopt::EvaP Long/short options, multilevel help Getopt::Long Advanced option handling Getopt::Mixed Supports both long and short options Getopt::Regex Option handling using regular expressions Getopt::Simple A simplified interface to Getopt::Long Getopt::Std Implements basic getopt and getopts Getopt::Tabular Table-driven argument parsing with help textEach of these is a Perl module for parsing the command line. They have been designed, written, debugged, and encapsulated. You don't have to write them again. They support standard interfaces. (Although there is perhaps a fine line between having non-standard interfaces and having 8 different standard interfaces.)
pr -l -n -a 10:30 foo bar pr -lna 10:30 foo bar pr -lna10:30 foo barTo use Getopt::Std, write
use Getopt::Std;
my %Options;
getopt('a', \%Options);
Getopt::Std exports the getopt() routine. getopt() takes two parameters: a string and a hash reference. The string lists all the options that take arguments. The hash receives the options found on the command line.
%Options = (l => 1, n => 1, a => '10:30') @ARGV = qw(foo bar)Getopt::Std also has another interface:
$ok = getopts('a:ln', \%Options);
Like getopt(), getopts() takes a string and a hash reference. The string includes all the option letters: both those that take arguments and those that do not. Option letters that take an argument are marked with a trailing colon. Because getopts() has a list of all the valid options, it can do some simple error checking: getopts() returns false if there are invalid options on the command line, and true otherwise.
pr --landscape --numbers --after 10:30 foo barHowever, Getopt::Long is not merely Getopt::Std with a facelift. It provides a large -- some would say bewildering -- assortment of facilities for parsing the command line in different ways. In addition, Getopt::Long has evolved over the last ten years, reflecting changes in the underlying Perl language, changes in programming style, and changes in interface style. At the same time, it maintains backward compatibility with previous versions.
$ok = GetOptions(\%Options, "landscape", "numbers!", "after=s");Each option specifier gives the name of an option, possibly followed by an argument specifier. The name will become a hash key. The argument specifier tells how to parse the argument to that option.
pr --nonumbers"after=s" takes a string argument; the argument will become the value of $Options{after}. "after:s" also takes a string argument, but the colon means that the argument is optional. Other argument specifiers are "=i" for integer arguments and "=f" for floating point arguments.
GetOptions(\%Options, "x=f@", "y=f@")will parse
graph --x 1 --x 2 --x 3 --y 1 --y 4 --y 9resulting in
%Options = (x => [1, 2, 3], y => [1, 4, 9])Similarly, if an argument specifier is suffixed with a '%', then the option takes key=value pairs, and the corresponding value in %Options becomes a reference to a hash of those pairs. So
GetOptions(\%Options, "define=s%")will parse Stroustrup's example
cc --define sqrt=rand --define exit=abort hello.ccresulting in
%Options = (define => { sqrt => 'rand',
exit => 'abort' })
cat -You don't have to store all the options in %Options. Each option can have its own linkage specification, which may be a scalar ref, an array ref, a hash ref, or a code ref. For scalar, array, and hash refs, the option is stored in the referenced variable. If the linkage specification is a code ref, the option isn't stored anywhere; instead, the option name and value are passed to the referenced subroutine.
pr --numbers foo --nonumbers barFinally, you can specify a code ref to process arguments that aren't options. This allows GetOptions() to process the entire command line, and potentially reduces your program to a single
GetOptions(...);call, plus subroutines.
$descriptions = { landscape => { type => '' },
numbers => { type => '' },
after => { type => '=s' } }
getOptions() is invoked as a method on a Getopt::Simple object:
$options = new Getopt::Simple; $options->getOptions($descriptions, "Usage: pr -landscape -numbers -after time");and options are retrieved through the $options object:
$option->{switch}{landscape} and ...
$option->{switch}{after } and ...
@options = (['-landscape', 'boolean', 0, \$landscape',
'print in landscape orientation'],
['-numbers' , 'boolean', 0, \$numbers' ,
'print page numbers'],
['-after' , 'string' , 1, \$time' ,
'print after time'],);
GetOptions(\@options, \@ARGV) or exit 1;
Each line in the table describes a single option, and specifies the option name, type, number of arguments, action to take, and help text. The simplest action is to set a scalar; Getopt::Tabular can also collect arguments from the command line and assign them to an array, or pass them to a subroutine.
SpoofGetOptions(\@options, \@ARGV)
parses the command line and checks it for errors, but doesn't take any action. This is particularly useful for programs that use subroutines to process arguments, because subroutines can do expensive or irreversible things.
pr --landscape -a 12:00 foo barThe programming interface is similar to Getopt::Long:
Getopt::Mixed::getOptions(@option_descriptions)There is also an iterative form, which allows the program to process options one at a time:
Getopt::Mixed::init(@option_descriptions);
while (($option, $value) = Getopt::Mixed::nextOption()) { ... }
Getopt::Mixed::cleanup();
The results are stored in global variables. Given the command line shown above, Getopt::Mixed would set
$opt_landscape = 1 $opt_a = '12:00'Non-options arguments are left in @ARGV.
$spec = q(-l Print in landscape mode { $landscape = 1 }
-n Print page numbers { $numbers = 1 }
-a Print after time { Queue($time) });
The string describes each option, along with help text and a BLOCK to be executed when the option is found.
$parser = new Getopt::Declare $spec;As written, this builds a parser and runs it on the command line; with additional arguments, it can parse strings or configuration files. Options and their values can be retrieved from $parser, but this is typically unnecessary, because the BLOCKs in the specification string contain arbitrary Perl code.
EvaP \@option_specs, \@help_text, \%optionsPerhaps the most interesting feature of Getopt::EvaP is that it has been implemented for Perl, Perl/Tk, Tcl and C. If you are developing in multiple languages, EvaP can provide a consistent user interface across all your applications.
GetOptions(\@ARGV, [$regex, \$scalar , $takesarg],
[$regex, sub {...} , $takesarg], ...);
For each option, the user passes an array ref. The first element is a regular expression, the second is either a scalar ref or a code ref, and the third indicates whether the option takes an argument.