1Getopt::Long(3pm)      Perl Programmers Reference Guide      Getopt::Long(3pm)
2
3
4

NAME

6       Getopt::Long - Extended processing of command line options
7

SYNOPSIS

9         use Getopt::Long;
10         my $data   = "file.dat";
11         my $length = 24;
12         my $verbose;
13         $result = GetOptions ("length=i" => \$length,    # numeric
14                               "file=s"   => \$data,      # string
15                               "verbose"  => \$verbose);  # flag
16

DESCRIPTION

18       The Getopt::Long module implements an extended getopt function called
19       GetOptions(). This function adheres to the POSIX syntax for command
20       line options, with GNU extensions. In general, this means that options
21       have long names instead of single letters, and are introduced with a
22       double dash "--". Support for bundling of command line options, as was
23       the case with the more traditional single-letter approach, is provided
24       but not enabled by default.
25

Command Line Options, an Introduction

27       Command line operated programs traditionally take their arguments from
28       the command line, for example filenames or other information that the
29       program needs to know. Besides arguments, these programs often take
30       command line options as well. Options are not necessary for the program
31       to work, hence the name 'option', but are used to modify its default
32       behaviour. For example, a program could do its job quietly, but with a
33       suitable option it could provide verbose information about what it did.
34
35       Command line options come in several flavours. Historically, they are
36       preceded by a single dash "-", and consist of a single letter.
37
38           -l -a -c
39
40       Usually, these single-character options can be bundled:
41
42           -lac
43
44       Options can have values, the value is placed after the option
45       character. Sometimes with whitespace in between, sometimes not:
46
47           -s 24 -s24
48
49       Due to the very cryptic nature of these options, another style was
50       developed that used long names. So instead of a cryptic "-l" one could
51       use the more descriptive "--long". To distinguish between a bundle of
52       single-character options and a long one, two dashes are used to precede
53       the option name. Early implementations of long options used a plus "+"
54       instead. Also, option values could be specified either like
55
56           --size=24
57
58       or
59
60           --size 24
61
62       The "+" form is now obsolete and strongly deprecated.
63

Getting Started with Getopt::Long

65       Getopt::Long is the Perl5 successor of "newgetopt.pl". This was the
66       first Perl module that provided support for handling the new style of
67       command line options, hence the name Getopt::Long. This module also
68       supports single-character options and bundling. Single character
69       options may be any alphabetic character, a question mark, and a dash.
70       Long options may consist of a series of letters, digits, and dashes.
71       Although this is currently not enforced by Getopt::Long, multiple
72       consecutive dashes are not allowed, and the option name must not end
73       with a dash.
74
75       To use Getopt::Long from a Perl program, you must include the following
76       line in your Perl program:
77
78           use Getopt::Long;
79
80       This will load the core of the Getopt::Long module and prepare your
81       program for using it. Most of the actual Getopt::Long code is not
82       loaded until you really call one of its functions.
83
84       In the default configuration, options names may be abbreviated to
85       uniqueness, case does not matter, and a single dash is sufficient, even
86       for long option names. Also, options may be placed between non-option
87       arguments. See "Configuring Getopt::Long" for more details on how to
88       configure Getopt::Long.
89
90   Simple options
91       The most simple options are the ones that take no values. Their mere
92       presence on the command line enables the option. Popular examples are:
93
94           --all --verbose --quiet --debug
95
96       Handling simple options is straightforward:
97
98           my $verbose = '';   # option variable with default value (false)
99           my $all = '';       # option variable with default value (false)
100           GetOptions ('verbose' => \$verbose, 'all' => \$all);
101
102       The call to GetOptions() parses the command line arguments that are
103       present in @ARGV and sets the option variable to the value 1 if the
104       option did occur on the command line. Otherwise, the option variable is
105       not touched. Setting the option value to true is often called enabling
106       the option.
107
108       The option name as specified to the GetOptions() function is called the
109       option specification. Later we'll see that this specification can
110       contain more than just the option name. The reference to the variable
111       is called the option destination.
112
113       GetOptions() will return a true value if the command line could be
114       processed successfully. Otherwise, it will write error messages to
115       STDERR, and return a false result.
116
117   A little bit less simple options
118       Getopt::Long supports two useful variants of simple options: negatable
119       options and incremental options.
120
121       A negatable option is specified with an exclamation mark "!" after the
122       option name:
123
124           my $verbose = '';   # option variable with default value (false)
125           GetOptions ('verbose!' => \$verbose);
126
127       Now, using "--verbose" on the command line will enable $verbose, as
128       expected. But it is also allowed to use "--noverbose", which will
129       disable $verbose by setting its value to 0. Using a suitable default
130       value, the program can find out whether $verbose is false by default,
131       or disabled by using "--noverbose".
132
133       An incremental option is specified with a plus "+" after the option
134       name:
135
136           my $verbose = '';   # option variable with default value (false)
137           GetOptions ('verbose+' => \$verbose);
138
139       Using "--verbose" on the command line will increment the value of
140       $verbose. This way the program can keep track of how many times the
141       option occurred on the command line. For example, each occurrence of
142       "--verbose" could increase the verbosity level of the program.
143
144   Mixing command line option with other arguments
145       Usually programs take command line options as well as other arguments,
146       for example, file names. It is good practice to always specify the
147       options first, and the other arguments last. Getopt::Long will,
148       however, allow the options and arguments to be mixed and 'filter out'
149       all the options before passing the rest of the arguments to the
150       program. To stop Getopt::Long from processing further arguments, insert
151       a double dash "--" on the command line:
152
153           --size 24 -- --all
154
155       In this example, "--all" will not be treated as an option, but passed
156       to the program unharmed, in @ARGV.
157
158   Options with values
159       For options that take values it must be specified whether the option
160       value is required or not, and what kind of value the option expects.
161
162       Three kinds of values are supported: integer numbers, floating point
163       numbers, and strings.
164
165       If the option value is required, Getopt::Long will take the command
166       line argument that follows the option and assign this to the option
167       variable. If, however, the option value is specified as optional, this
168       will only be done if that value does not look like a valid command line
169       option itself.
170
171           my $tag = '';       # option variable with default value
172           GetOptions ('tag=s' => \$tag);
173
174       In the option specification, the option name is followed by an equals
175       sign "=" and the letter "s". The equals sign indicates that this option
176       requires a value. The letter "s" indicates that this value is an
177       arbitrary string. Other possible value types are "i" for integer
178       values, and "f" for floating point values. Using a colon ":" instead of
179       the equals sign indicates that the option value is optional. In this
180       case, if no suitable value is supplied, string valued options get an
181       empty string '' assigned, while numeric options are set to 0.
182
183   Options with multiple values
184       Options sometimes take several values. For example, a program could use
185       multiple directories to search for library files:
186
187           --library lib/stdlib --library lib/extlib
188
189       To accomplish this behaviour, simply specify an array reference as the
190       destination for the option:
191
192           GetOptions ("library=s" => \@libfiles);
193
194       Alternatively, you can specify that the option can have multiple values
195       by adding a "@", and pass a scalar reference as the destination:
196
197           GetOptions ("library=s@" => \$libfiles);
198
199       Used with the example above, @libfiles (or @$libfiles) would contain
200       two strings upon completion: "lib/srdlib" and "lib/extlib", in that
201       order. It is also possible to specify that only integer or floating
202       point numbers are acceptable values.
203
204       Often it is useful to allow comma-separated lists of values as well as
205       multiple occurrences of the options. This is easy using Perl's split()
206       and join() operators:
207
208           GetOptions ("library=s" => \@libfiles);
209           @libfiles = split(/,/,join(',',@libfiles));
210
211       Of course, it is important to choose the right separator string for
212       each purpose.
213
214       Warning: What follows is an experimental feature.
215
216       Options can take multiple values at once, for example
217
218           --coordinates 52.2 16.4 --rgbcolor 255 255 149
219
220       This can be accomplished by adding a repeat specifier to the option
221       specification. Repeat specifiers are very similar to the "{...}" repeat
222       specifiers that can be used with regular expression patterns.  For
223       example, the above command line would be handled as follows:
224
225           GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);
226
227       The destination for the option must be an array or array reference.
228
229       It is also possible to specify the minimal and maximal number of
230       arguments an option takes. "foo=s{2,4}" indicates an option that takes
231       at least two and at most 4 arguments. "foo=s{,}" indicates one or more
232       values; "foo:s{,}" indicates zero or more option values.
233
234   Options with hash values
235       If the option destination is a reference to a hash, the option will
236       take, as value, strings of the form key"="value. The value will be
237       stored with the specified key in the hash.
238
239           GetOptions ("define=s" => \%defines);
240
241       Alternatively you can use:
242
243           GetOptions ("define=s%" => \$defines);
244
245       When used with command line options:
246
247           --define os=linux --define vendor=redhat
248
249       the hash %defines (or %$defines) will contain two keys, "os" with value
250       "linux" and "vendor" with value "redhat". It is also possible to
251       specify that only integer or floating point numbers are acceptable
252       values. The keys are always taken to be strings.
253
254   User-defined subroutines to handle options
255       Ultimate control over what should be done when (actually: each time) an
256       option is encountered on the command line can be achieved by
257       designating a reference to a subroutine (or an anonymous subroutine) as
258       the option destination. When GetOptions() encounters the option, it
259       will call the subroutine with two or three arguments. The first
260       argument is the name of the option. (Actually, it is an object that
261       stringifies to the name of the option.) For a scalar or array
262       destination, the second argument is the value to be stored. For a hash
263       destination, the second arguments is the key to the hash, and the third
264       argument the value to be stored. It is up to the subroutine to store
265       the value, or do whatever it thinks is appropriate.
266
267       A trivial application of this mechanism is to implement options that
268       are related to each other. For example:
269
270           my $verbose = '';   # option variable with default value (false)
271           GetOptions ('verbose' => \$verbose,
272                       'quiet'   => sub { $verbose = 0 });
273
274       Here "--verbose" and "--quiet" control the same variable $verbose, but
275       with opposite values.
276
277       If the subroutine needs to signal an error, it should call die() with
278       the desired error message as its argument. GetOptions() will catch the
279       die(), issue the error message, and record that an error result must be
280       returned upon completion.
281
282       If the text of the error message starts with an exclamation mark "!"
283       it is interpreted specially by GetOptions(). There is currently one
284       special command implemented: "die("!FINISH")" will cause GetOptions()
285       to stop processing options, as if it encountered a double dash "--".
286
287       In version 2.37 the first argument to the callback function was changed
288       from string to object. This was done to make room for extensions and
289       more detailed control. The object stringifies to the option name so
290       this change should not introduce compatibility problems.
291
292   Options with multiple names
293       Often it is user friendly to supply alternate mnemonic names for
294       options. For example "--height" could be an alternate name for
295       "--length". Alternate names can be included in the option
296       specification, separated by vertical bar "|" characters. To implement
297       the above example:
298
299           GetOptions ('length|height=f' => \$length);
300
301       The first name is called the primary name, the other names are called
302       aliases. When using a hash to store options, the key will always be the
303       primary name.
304
305       Multiple alternate names are possible.
306
307   Case and abbreviations
308       Without additional configuration, GetOptions() will ignore the case of
309       option names, and allow the options to be abbreviated to uniqueness.
310
311           GetOptions ('length|height=f' => \$length, "head" => \$head);
312
313       This call will allow "--l" and "--L" for the length option, but
314       requires a least "--hea" and "--hei" for the head and height options.
315
316   Summary of Option Specifications
317       Each option specifier consists of two parts: the name specification and
318       the argument specification.
319
320       The name specification contains the name of the option, optionally
321       followed by a list of alternative names separated by vertical bar
322       characters.
323
324           length            option name is "length"
325           length|size|l     name is "length", aliases are "size" and "l"
326
327       The argument specification is optional. If omitted, the option is
328       considered boolean, a value of 1 will be assigned when the option is
329       used on the command line.
330
331       The argument specification can be
332
333       !   The option does not take an argument and may be negated by
334           prefixing it with "no" or "no-". E.g. "foo!" will allow "--foo" (a
335           value of 1 will be assigned) as well as "--nofoo" and "--no-foo" (a
336           value of 0 will be assigned). If the option has aliases, this
337           applies to the aliases as well.
338
339           Using negation on a single letter option when bundling is in effect
340           is pointless and will result in a warning.
341
342       +   The option does not take an argument and will be incremented by 1
343           every time it appears on the command line. E.g. "more+", when used
344           with "--more --more --more", will increment the value three times,
345           resulting in a value of 3 (provided it was 0 or undefined at
346           first).
347
348           The "+" specifier is ignored if the option destination is not a
349           scalar.
350
351       = type [ desttype ] [ repeat ]
352           The option requires an argument of the given type. Supported types
353           are:
354
355           s   String. An arbitrary sequence of characters. It is valid for
356               the argument to start with "-" or "--".
357
358           i   Integer. An optional leading plus or minus sign, followed by a
359               sequence of digits.
360
361           o   Extended integer, Perl style. This can be either an optional
362               leading plus or minus sign, followed by a sequence of digits,
363               or an octal string (a zero, optionally followed by '0', '1', ..
364               '7'), or a hexadecimal string ("0x" followed by '0' .. '9', 'a'
365               .. 'f', case insensitive), or a binary string ("0b" followed by
366               a series of '0' and '1').
367
368           f   Real number. For example 3.14, "-6.23E24" and so on.
369
370           The desttype can be "@" or "%" to specify that the option is list
371           or a hash valued. This is only needed when the destination for the
372           option value is not otherwise specified. It should be omitted when
373           not needed.
374
375           The repeat specifies the number of values this option takes per
376           occurrence on the command line. It has the format "{" [ min ] [ ","
377           [ max ] ] "}".
378
379           min denotes the minimal number of arguments. It defaults to 1 for
380           options with "=" and to 0 for options with ":", see below. Note
381           that min overrules the "=" / ":" semantics.
382
383           max denotes the maximum number of arguments. It must be at least
384           min. If max is omitted, but the comma is not, there is no upper
385           bound to the number of argument values taken.
386
387       : type [ desttype ]
388           Like "=", but designates the argument as optional.  If omitted, an
389           empty string will be assigned to string values options, and the
390           value zero to numeric options.
391
392           Note that if a string argument starts with "-" or "--", it will be
393           considered an option on itself.
394
395       : number [ desttype ]
396           Like ":i", but if the value is omitted, the number will be
397           assigned.
398
399       : + [ desttype ]
400           Like ":i", but if the value is omitted, the current value for the
401           option will be incremented.
402

Advanced Possibilities

404   Object oriented interface
405       Getopt::Long can be used in an object oriented way as well:
406
407           use Getopt::Long;
408           $p = new Getopt::Long::Parser;
409           $p->configure(...configuration options...);
410           if ($p->getoptions(...options descriptions...)) ...
411
412       Configuration options can be passed to the constructor:
413
414           $p = new Getopt::Long::Parser
415                    config => [...configuration options...];
416
417   Thread Safety
418       Getopt::Long is thread safe when using ithreads as of Perl 5.8.  It is
419       not thread safe when using the older (experimental and now obsolete)
420       threads implementation that was added to Perl 5.005.
421
422   Documentation and help texts
423       Getopt::Long encourages the use of Pod::Usage to produce help messages.
424       For example:
425
426           use Getopt::Long;
427           use Pod::Usage;
428
429           my $man = 0;
430           my $help = 0;
431
432           GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
433           pod2usage(1) if $help;
434           pod2usage(-exitstatus => 0, -verbose => 2) if $man;
435
436           __END__
437
438           =head1 NAME
439
440           sample - Using Getopt::Long and Pod::Usage
441
442           =head1 SYNOPSIS
443
444           sample [options] [file ...]
445
446            Options:
447              -help            brief help message
448              -man             full documentation
449
450           =head1 OPTIONS
451
452           =over 8
453
454           =item B<-help>
455
456           Print a brief help message and exits.
457
458           =item B<-man>
459
460           Prints the manual page and exits.
461
462           =back
463
464           =head1 DESCRIPTION
465
466           B<This program> will read the given input file(s) and do something
467           useful with the contents thereof.
468
469           =cut
470
471       See Pod::Usage for details.
472
473   Parsing options from an arbitrary array
474       By default, GetOptions parses the options that are present in the
475       global array @ARGV. A special entry "GetOptionsFromArray" can be used
476       to parse options from an arbitrary array.
477
478           use Getopt::Long qw(GetOptionsFromArray);
479           $ret = GetOptionsFromArray(\@myopts, ...);
480
481       When used like this, the global @ARGV is not touched at all.
482
483       The following two calls behave identically:
484
485           $ret = GetOptions( ... );
486           $ret = GetOptionsFromArray(\@ARGV, ... );
487
488   Parsing options from an arbitrary string
489       A special entry "GetOptionsFromString" can be used to parse options
490       from an arbitrary string.
491
492           use Getopt::Long qw(GetOptionsFromString);
493           $ret = GetOptionsFromString($string, ...);
494
495       The contents of the string are split into arguments using a call to
496       "Text::ParseWords::shellwords". As with "GetOptionsFromArray", the
497       global @ARGV is not touched.
498
499       It is possible that, upon completion, not all arguments in the string
500       have been processed. "GetOptionsFromString" will, when called in list
501       context, return both the return status and an array reference to any
502       remaining arguments:
503
504           ($ret, $args) = GetOptionsFromString($string, ... );
505
506       If any arguments remain, and "GetOptionsFromString" was not called in
507       list context, a message will be given and "GetOptionsFromString" will
508       return failure.
509
510   Storing options values in a hash
511       Sometimes, for example when there are a lot of options, having a
512       separate variable for each of them can be cumbersome. GetOptions()
513       supports, as an alternative mechanism, storing options values in a
514       hash.
515
516       To obtain this, a reference to a hash must be passed as the first
517       argument to GetOptions(). For each option that is specified on the
518       command line, the option value will be stored in the hash with the
519       option name as key. Options that are not actually used on the command
520       line will not be put in the hash, on other words, "exists($h{option})"
521       (or defined()) can be used to test if an option was used. The drawback
522       is that warnings will be issued if the program runs under "use strict"
523       and uses $h{option} without testing with exists() or defined() first.
524
525           my %h = ();
526           GetOptions (\%h, 'length=i');       # will store in $h{length}
527
528       For options that take list or hash values, it is necessary to indicate
529       this by appending an "@" or "%" sign after the type:
530
531           GetOptions (\%h, 'colours=s@');     # will push to @{$h{colours}}
532
533       To make things more complicated, the hash may contain references to the
534       actual destinations, for example:
535
536           my $len = 0;
537           my %h = ('length' => \$len);
538           GetOptions (\%h, 'length=i');       # will store in $len
539
540       This example is fully equivalent with:
541
542           my $len = 0;
543           GetOptions ('length=i' => \$len);   # will store in $len
544
545       Any mixture is possible. For example, the most frequently used options
546       could be stored in variables while all other options get stored in the
547       hash:
548
549           my $verbose = 0;                    # frequently referred
550           my $debug = 0;                      # frequently referred
551           my %h = ('verbose' => \$verbose, 'debug' => \$debug);
552           GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
553           if ( $verbose ) { ... }
554           if ( exists $h{filter} ) { ... option 'filter' was specified ... }
555
556   Bundling
557       With bundling it is possible to set several single-character options at
558       once. For example if "a", "v" and "x" are all valid options,
559
560           -vax
561
562       would set all three.
563
564       Getopt::Long supports two levels of bundling. To enable bundling, a
565       call to Getopt::Long::Configure is required.
566
567       The first level of bundling can be enabled with:
568
569           Getopt::Long::Configure ("bundling");
570
571       Configured this way, single-character options can be bundled but long
572       options must always start with a double dash "--" to avoid ambiguity.
573       For example, when "vax", "a", "v" and "x" are all valid options,
574
575           -vax
576
577       would set "a", "v" and "x", but
578
579           --vax
580
581       would set "vax".
582
583       The second level of bundling lifts this restriction. It can be enabled
584       with:
585
586           Getopt::Long::Configure ("bundling_override");
587
588       Now, "-vax" would set the option "vax".
589
590       When any level of bundling is enabled, option values may be inserted in
591       the bundle. For example:
592
593           -h24w80
594
595       is equivalent to
596
597           -h 24 -w 80
598
599       When configured for bundling, single-character options are matched case
600       sensitive while long options are matched case insensitive. To have the
601       single-character options matched case insensitive as well, use:
602
603           Getopt::Long::Configure ("bundling", "ignorecase_always");
604
605       It goes without saying that bundling can be quite confusing.
606
607   The lonesome dash
608       Normally, a lone dash "-" on the command line will not be considered an
609       option. Option processing will terminate (unless "permute" is
610       configured) and the dash will be left in @ARGV.
611
612       It is possible to get special treatment for a lone dash. This can be
613       achieved by adding an option specification with an empty name, for
614       example:
615
616           GetOptions ('' => \$stdio);
617
618       A lone dash on the command line will now be a legal option, and using
619       it will set variable $stdio.
620
621   Argument callback
622       A special option 'name' "<>" can be used to designate a subroutine to
623       handle non-option arguments. When GetOptions() encounters an argument
624       that does not look like an option, it will immediately call this
625       subroutine and passes it one parameter: the argument name. Well,
626       actually it is an object that stringifies to the argument name.
627
628       For example:
629
630           my $width = 80;
631           sub process { ... }
632           GetOptions ('width=i' => \$width, '<>' => \&process);
633
634       When applied to the following command line:
635
636           arg1 --width=72 arg2 --width=60 arg3
637
638       This will call "process("arg1")" while $width is 80, "process("arg2")"
639       while $width is 72, and "process("arg3")" while $width is 60.
640
641       This feature requires configuration option permute, see section
642       "Configuring Getopt::Long".
643

Configuring Getopt::Long

645       Getopt::Long can be configured by calling subroutine
646       Getopt::Long::Configure(). This subroutine takes a list of quoted
647       strings, each specifying a configuration option to be enabled, e.g.
648       "ignore_case", or disabled, e.g. "no_ignore_case". Case does not
649       matter. Multiple calls to Configure() are possible.
650
651       Alternatively, as of version 2.24, the configuration options may be
652       passed together with the "use" statement:
653
654           use Getopt::Long qw(:config no_ignore_case bundling);
655
656       The following options are available:
657
658       default     This option causes all configuration options to be reset to
659                   their default values.
660
661       posix_default
662                   This option causes all configuration options to be reset to
663                   their default values as if the environment variable
664                   POSIXLY_CORRECT had been set.
665
666       auto_abbrev Allow option names to be abbreviated to uniqueness.
667                   Default is enabled unless environment variable
668                   POSIXLY_CORRECT has been set, in which case "auto_abbrev"
669                   is disabled.
670
671       getopt_compat
672                   Allow "+" to start options.  Default is enabled unless
673                   environment variable POSIXLY_CORRECT has been set, in which
674                   case "getopt_compat" is disabled.
675
676       gnu_compat  "gnu_compat" controls whether "--opt=" is allowed, and what
677                   it should do. Without "gnu_compat", "--opt=" gives an
678                   error. With "gnu_compat", "--opt=" will give option "opt"
679                   and empty value.  This is the way GNU getopt_long() does
680                   it.
681
682       gnu_getopt  This is a short way of setting "gnu_compat" "bundling"
683                   "permute" "no_getopt_compat". With "gnu_getopt", command
684                   line handling should be fully compatible with GNU
685                   getopt_long().
686
687       require_order
688                   Whether command line arguments are allowed to be mixed with
689                   options.  Default is disabled unless environment variable
690                   POSIXLY_CORRECT has been set, in which case "require_order"
691                   is enabled.
692
693                   See also "permute", which is the opposite of
694                   "require_order".
695
696       permute     Whether command line arguments are allowed to be mixed with
697                   options.  Default is enabled unless environment variable
698                   POSIXLY_CORRECT has been set, in which case "permute" is
699                   disabled.  Note that "permute" is the opposite of
700                   "require_order".
701
702                   If "permute" is enabled, this means that
703
704                       --foo arg1 --bar arg2 arg3
705
706                   is equivalent to
707
708                       --foo --bar arg1 arg2 arg3
709
710                   If an argument callback routine is specified, @ARGV will
711                   always be empty upon successful return of GetOptions()
712                   since all options have been processed. The only exception
713                   is when "--" is used:
714
715                       --foo arg1 --bar arg2 -- arg3
716
717                   This will call the callback routine for arg1 and arg2, and
718                   then terminate GetOptions() leaving "arg3" in @ARGV.
719
720                   If "require_order" is enabled, options processing
721                   terminates when the first non-option is encountered.
722
723                       --foo arg1 --bar arg2 arg3
724
725                   is equivalent to
726
727                       --foo -- arg1 --bar arg2 arg3
728
729                   If "pass_through" is also enabled, options processing will
730                   terminate at the first unrecognized option, or non-option,
731                   whichever comes first.
732
733       bundling (default: disabled)
734                   Enabling this option will allow single-character options to
735                   be bundled. To distinguish bundles from long option names,
736                   long options must be introduced with "--" and bundles with
737                   "-".
738
739                   Note that, if you have options "a", "l" and "all", and
740                   auto_abbrev enabled, possible arguments and option settings
741                   are:
742
743                       using argument               sets option(s)
744                       ------------------------------------------
745                       -a, --a                      a
746                       -l, --l                      l
747                       -al, -la, -ala, -all,...     a, l
748                       --al, --all                  all
749
750                   The surprising part is that "--a" sets option "a" (due to
751                   auto completion), not "all".
752
753                   Note: disabling "bundling" also disables
754                   "bundling_override".
755
756       bundling_override (default: disabled)
757                   If "bundling_override" is enabled, bundling is enabled as
758                   with "bundling" but now long option names override option
759                   bundles.
760
761                   Note: disabling "bundling_override" also disables
762                   "bundling".
763
764                   Note: Using option bundling can easily lead to unexpected
765                   results, especially when mixing long options and bundles.
766                   Caveat emptor.
767
768       ignore_case  (default: enabled)
769                   If enabled, case is ignored when matching long option
770                   names. If, however, bundling is enabled as well, single
771                   character options will be treated case-sensitive.
772
773                   With "ignore_case", option specifications for options that
774                   only differ in case, e.g., "foo" and "Foo", will be flagged
775                   as duplicates.
776
777                   Note: disabling "ignore_case" also disables
778                   "ignore_case_always".
779
780       ignore_case_always (default: disabled)
781                   When bundling is in effect, case is ignored on single-
782                   character options also.
783
784                   Note: disabling "ignore_case_always" also disables
785                   "ignore_case".
786
787       auto_version (default:disabled)
788                   Automatically provide support for the --version option if
789                   the application did not specify a handler for this option
790                   itself.
791
792                   Getopt::Long will provide a standard version message that
793                   includes the program name, its version (if $main::VERSION
794                   is defined), and the versions of Getopt::Long and Perl. The
795                   message will be written to standard output and processing
796                   will terminate.
797
798                   "auto_version" will be enabled if the calling program
799                   explicitly specified a version number higher than 2.32 in
800                   the "use" or "require" statement.
801
802       auto_help (default:disabled)
803                   Automatically provide support for the --help and -? options
804                   if the application did not specify a handler for this
805                   option itself.
806
807                   Getopt::Long will provide a help message using module
808                   Pod::Usage. The message, derived from the SYNOPSIS POD
809                   section, will be written to standard output and processing
810                   will terminate.
811
812                   "auto_help" will be enabled if the calling program
813                   explicitly specified a version number higher than 2.32 in
814                   the "use" or "require" statement.
815
816       pass_through (default: disabled)
817                   Options that are unknown, ambiguous or supplied with an
818                   invalid option value are passed through in @ARGV instead of
819                   being flagged as errors. This makes it possible to write
820                   wrapper scripts that process only part of the user supplied
821                   command line arguments, and pass the remaining options to
822                   some other program.
823
824                   If "require_order" is enabled, options processing will
825                   terminate at the first unrecognized option, or non-option,
826                   whichever comes first.  However, if "permute" is enabled
827                   instead, results can become confusing.
828
829                   Note that the options terminator (default "--"), if
830                   present, will also be passed through in @ARGV.
831
832       prefix      The string that starts options. If a constant string is not
833                   sufficient, see "prefix_pattern".
834
835       prefix_pattern
836                   A Perl pattern that identifies the strings that introduce
837                   options.  Default is "--|-|\+" unless environment variable
838                   POSIXLY_CORRECT has been set, in which case it is "--|-".
839
840       long_prefix_pattern
841                   A Perl pattern that allows the disambiguation of long and
842                   short prefixes. Default is "--".
843
844                   Typically you only need to set this if you are using
845                   nonstandard prefixes and want some or all of them to have
846                   the same semantics as '--' does under normal circumstances.
847
848                   For example, setting prefix_pattern to "--|-|\+|\/" and
849                   long_prefix_pattern to "--|\/" would add Win32 style
850                   argument handling.
851
852       debug (default: disabled)
853                   Enable debugging output.
854

Exportable Methods

856       VersionMessage
857           This subroutine provides a standard version message. Its argument
858           can be:
859
860           ·   A string containing the text of a message to print before
861               printing the standard message.
862
863           ·   A numeric value corresponding to the desired exit status.
864
865           ·   A reference to a hash.
866
867           If more than one argument is given then the entire argument list is
868           assumed to be a hash.  If a hash is supplied (either as a reference
869           or as a list) it should contain one or more elements with the
870           following keys:
871
872           "-message"
873           "-msg"
874               The text of a message to print immediately prior to printing
875               the program's usage message.
876
877           "-exitval"
878               The desired exit status to pass to the exit() function.  This
879               should be an integer, or else the string "NOEXIT" to indicate
880               that control should simply be returned without terminating the
881               invoking process.
882
883           "-output"
884               A reference to a filehandle, or the pathname of a file to which
885               the usage message should be written. The default is "\*STDERR"
886               unless the exit value is less than 2 (in which case the default
887               is "\*STDOUT").
888
889           You cannot tie this routine directly to an option, e.g.:
890
891               GetOptions("version" => \&VersionMessage);
892
893           Use this instead:
894
895               GetOptions("version" => sub { VersionMessage() });
896
897       HelpMessage
898           This subroutine produces a standard help message, derived from the
899           program's POD section SYNOPSIS using Pod::Usage. It takes the same
900           arguments as VersionMessage(). In particular, you cannot tie it
901           directly to an option, e.g.:
902
903               GetOptions("help" => \&HelpMessage);
904
905           Use this instead:
906
907               GetOptions("help" => sub { HelpMessage() });
908

Return values and Errors

910       Configuration errors and errors in the option definitions are signalled
911       using die() and will terminate the calling program unless the call to
912       Getopt::Long::GetOptions() was embedded in "eval { ...  }", or die()
913       was trapped using $SIG{__DIE__}.
914
915       GetOptions returns true to indicate success.  It returns false when the
916       function detected one or more errors during option parsing. These
917       errors are signalled using warn() and can be trapped with
918       $SIG{__WARN__}.
919

Legacy

921       The earliest development of "newgetopt.pl" started in 1990, with Perl
922       version 4. As a result, its development, and the development of
923       Getopt::Long, has gone through several stages. Since backward
924       compatibility has always been extremely important, the current version
925       of Getopt::Long still supports a lot of constructs that nowadays are no
926       longer necessary or otherwise unwanted. This section describes briefly
927       some of these 'features'.
928
929   Default destinations
930       When no destination is specified for an option, GetOptions will store
931       the resultant value in a global variable named "opt_"XXX, where XXX is
932       the primary name of this option. When a progam executes under "use
933       strict" (recommended), these variables must be pre-declared with our()
934       or "use vars".
935
936           our $opt_length = 0;
937           GetOptions ('length=i');    # will store in $opt_length
938
939       To yield a usable Perl variable, characters that are not part of the
940       syntax for variables are translated to underscores. For example,
941       "--fpp-struct-return" will set the variable $opt_fpp_struct_return.
942       Note that this variable resides in the namespace of the calling
943       program, not necessarily "main". For example:
944
945           GetOptions ("size=i", "sizes=i@");
946
947       with command line "-size 10 -sizes 24 -sizes 48" will perform the
948       equivalent of the assignments
949
950           $opt_size = 10;
951           @opt_sizes = (24, 48);
952
953   Alternative option starters
954       A string of alternative option starter characters may be passed as the
955       first argument (or the first argument after a leading hash reference
956       argument).
957
958           my $len = 0;
959           GetOptions ('/', 'length=i' => $len);
960
961       Now the command line may look like:
962
963           /length 24 -- arg
964
965       Note that to terminate options processing still requires a double dash
966       "--".
967
968       GetOptions() will not interpret a leading "<>" as option starters if
969       the next argument is a reference. To force "<" and ">" as option
970       starters, use "><". Confusing? Well, using a starter argument is
971       strongly deprecated anyway.
972
973   Configuration variables
974       Previous versions of Getopt::Long used variables for the purpose of
975       configuring. Although manipulating these variables still work, it is
976       strongly encouraged to use the "Configure" routine that was introduced
977       in version 2.17. Besides, it is much easier.
978

Tips and Techniques

980   Pushing multiple values in a hash option
981       Sometimes you want to combine the best of hashes and arrays. For
982       example, the command line:
983
984         --list add=first --list add=second --list add=third
985
986       where each successive 'list add' option will push the value of add into
987       array ref $list->{'add'}. The result would be like
988
989         $list->{add} = [qw(first second third)];
990
991       This can be accomplished with a destination routine:
992
993         GetOptions('list=s%' =>
994                      sub { push(@{$list{$_[1]}}, $_[2]) });
995

Troubleshooting

997   GetOptions does not return a false result when an option is not supplied
998       That's why they're called 'options'.
999
1000   GetOptions does not split the command line correctly
1001       The command line is not split by GetOptions, but by the command line
1002       interpreter (CLI). On Unix, this is the shell. On Windows, it is
1003       COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
1004
1005       It is important to know that these CLIs may behave different when the
1006       command line contains special characters, in particular quotes or
1007       backslashes. For example, with Unix shells you can use single quotes
1008       ("'") and double quotes (""") to group words together. The following
1009       alternatives are equivalent on Unix:
1010
1011           "two words"
1012           'two words'
1013           two\ words
1014
1015       In case of doubt, insert the following statement in front of your Perl
1016       program:
1017
1018           print STDERR (join("|",@ARGV),"\n");
1019
1020       to verify how your CLI passes the arguments to the program.
1021
1022   Undefined subroutine &main::GetOptions called
1023       Are you running Windows, and did you write
1024
1025           use GetOpt::Long;
1026
1027       (note the capital 'O')?
1028
1029   How do I put a "-?" option into a Getopt::Long?
1030       You can only obtain this using an alias, and Getopt::Long of at least
1031       version 2.13.
1032
1033           use Getopt::Long;
1034           GetOptions ("help|?");    # -help and -? will both set $opt_help
1035

AUTHOR

1037       Johan Vromans <jvromans@squirrel.nl>
1038
1040       This program is Copyright 1990,2009 by Johan Vromans.  This program is
1041       free software; you can redistribute it and/or modify it under the terms
1042       of the Perl Artistic License or the GNU General Public License as
1043       published by the Free Software Foundation; either version 2 of the
1044       License, or (at your option) any later version.
1045
1046       This program is distributed in the hope that it will be useful, but
1047       WITHOUT ANY WARRANTY; without even the implied warranty of
1048       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1049       General Public License for more details.
1050
1051       If you do not have a copy of the GNU General Public License write to
1052       the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
1053       USA.
1054
1055
1056
1057perl v5.12.4                      2011-06-01                 Getopt::Long(3pm)
Impressum