1Getopt::Long(3)       User Contributed Perl Documentation      Getopt::Long(3)
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         GetOptions ("length=i" => \$length,    # numeric
14                     "file=s"   => \$data,      # string
15                     "verbose"  => \$verbose)   # flag
16         or die("Error in command line arguments\n");
17

DESCRIPTION

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

Command Line Options, an Introduction

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

Getting Started with Getopt::Long

69       Getopt::Long is the Perl5 successor of "newgetopt.pl". This was the
70       first Perl module that provided support for handling the new style of
71       command line options, in particular long option names, hence the Perl5
72       name Getopt::Long. This module also supports single-character options
73       and bundling.
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 using
115       die() and warn(), 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/stdlib" 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{1,}" 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 argument 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       Here is an example of how to access the option name and value from
293       within a subroutine:
294
295           GetOptions ('opt=i' => \&handler);
296           sub handler {
297               my ($opt_name, $opt_value) = @_;
298               print("Option name is $opt_name and value is $opt_value\n");
299           }
300
301   Options with multiple names
302       Often it is user friendly to supply alternate mnemonic names for
303       options. For example "--height" could be an alternate name for
304       "--length". Alternate names can be included in the option
305       specification, separated by vertical bar "|" characters. To implement
306       the above example:
307
308           GetOptions ('length|height=f' => \$length);
309
310       The first name is called the primary name, the other names are called
311       aliases. When using a hash to store options, the key will always be the
312       primary name.
313
314       Multiple alternate names are possible.
315
316   Case and abbreviations
317       Without additional configuration, GetOptions() will ignore the case of
318       option names, and allow the options to be abbreviated to uniqueness.
319
320           GetOptions ('length|height=f' => \$length, "head" => \$head);
321
322       This call will allow "--l" and "--L" for the length option, but
323       requires a least "--hea" and "--hei" for the head and height options.
324
325   Summary of Option Specifications
326       Each option specifier consists of two parts: the name specification and
327       the argument specification.
328
329       The name specification contains the name of the option, optionally
330       followed by a list of alternative names separated by vertical bar
331       characters.
332
333           length            option name is "length"
334           length|size|l     name is "length", aliases are "size" and "l"
335
336       The argument specification is optional. If omitted, the option is
337       considered boolean, a value of 1 will be assigned when the option is
338       used on the command line.
339
340       The argument specification can be
341
342       !   The option does not take an argument and may be negated by
343           prefixing it with "no" or "no-". E.g. "foo!" will allow "--foo" (a
344           value of 1 will be assigned) as well as "--nofoo" and "--no-foo" (a
345           value of 0 will be assigned). If the option has aliases, this
346           applies to the aliases as well.
347
348           Using negation on a single letter option when bundling is in effect
349           is pointless and will result in a warning.
350
351       +   The option does not take an argument and will be incremented by 1
352           every time it appears on the command line. E.g. "more+", when used
353           with "--more --more --more", will increment the value three times,
354           resulting in a value of 3 (provided it was 0 or undefined at
355           first).
356
357           The "+" specifier is ignored if the option destination is not a
358           scalar.
359
360       = type [ desttype ] [ repeat ]
361           The option requires an argument of the given type. Supported types
362           are:
363
364           s   String. An arbitrary sequence of characters. It is valid for
365               the argument to start with "-" or "--".
366
367           i   Integer. An optional leading plus or minus sign, followed by a
368               sequence of digits.
369
370           o   Extended integer, Perl style. This can be either an optional
371               leading plus or minus sign, followed by a sequence of digits,
372               or an octal string (a zero, optionally followed by '0', '1', ..
373               '7'), or a hexadecimal string ("0x" followed by '0' .. '9', 'a'
374               .. 'f', case insensitive), or a binary string ("0b" followed by
375               a series of '0' and '1').
376
377           f   Real number. For example 3.14, "-6.23E24" and so on.
378
379           The desttype can be "@" or "%" to specify that the option is list
380           or a hash valued. This is only needed when the destination for the
381           option value is not otherwise specified. It should be omitted when
382           not needed.
383
384           The repeat specifies the number of values this option takes per
385           occurrence on the command line. It has the format "{" [ min ] [ ","
386           [ max ] ] "}".
387
388           min denotes the minimal number of arguments. It defaults to 1 for
389           options with "=" and to 0 for options with ":", see below. Note
390           that min overrules the "=" / ":" semantics.
391
392           max denotes the maximum number of arguments. It must be at least
393           min. If max is omitted, but the comma is not, there is no upper
394           bound to the number of argument values taken.
395
396       : type [ desttype ]
397           Like "=", but designates the argument as optional.  If omitted, an
398           empty string will be assigned to string values options, and the
399           value zero to numeric options.
400
401           Note that if a string argument starts with "-" or "--", it will be
402           considered an option on itself.
403
404       : number [ desttype ]
405           Like ":i", but if the value is omitted, the number will be
406           assigned.
407
408       : + [ desttype ]
409           Like ":i", but if the value is omitted, the current value for the
410           option will be incremented.
411

Advanced Possibilities

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

Configuring Getopt::Long

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

Exportable Methods

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

Return values and Errors

930       Configuration errors and errors in the option definitions are signalled
931       using die() and will terminate the calling program unless the call to
932       Getopt::Long::GetOptions() was embedded in "eval { ...  }", or die()
933       was trapped using $SIG{__DIE__}.
934
935       GetOptions returns true to indicate success.  It returns false when the
936       function detected one or more errors during option parsing. These
937       errors are signalled using warn() and can be trapped with
938       $SIG{__WARN__}.
939

Legacy

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

Tips and Techniques

1000   Pushing multiple values in a hash option
1001       Sometimes you want to combine the best of hashes and arrays. For
1002       example, the command line:
1003
1004         --list add=first --list add=second --list add=third
1005
1006       where each successive 'list add' option will push the value of add into
1007       array ref $list->{'add'}. The result would be like
1008
1009         $list->{add} = [qw(first second third)];
1010
1011       This can be accomplished with a destination routine:
1012
1013         GetOptions('list=s%' =>
1014                      sub { push(@{$list{$_[1]}}, $_[2]) });
1015

Troubleshooting

1017   GetOptions does not return a false result when an option is not supplied
1018       That's why they're called 'options'.
1019
1020   GetOptions does not split the command line correctly
1021       The command line is not split by GetOptions, but by the command line
1022       interpreter (CLI). On Unix, this is the shell. On Windows, it is
1023       COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
1024
1025       It is important to know that these CLIs may behave different when the
1026       command line contains special characters, in particular quotes or
1027       backslashes. For example, with Unix shells you can use single quotes
1028       ("'") and double quotes (""") to group words together. The following
1029       alternatives are equivalent on Unix:
1030
1031           "two words"
1032           'two words'
1033           two\ words
1034
1035       In case of doubt, insert the following statement in front of your Perl
1036       program:
1037
1038           print STDERR (join("|",@ARGV),"\n");
1039
1040       to verify how your CLI passes the arguments to the program.
1041
1042   Undefined subroutine &main::GetOptions called
1043       Are you running Windows, and did you write
1044
1045           use GetOpt::Long;
1046
1047       (note the capital 'O')?
1048
1049   How do I put a "-?" option into a Getopt::Long?
1050       You can only obtain this using an alias, and Getopt::Long of at least
1051       version 2.13.
1052
1053           use Getopt::Long;
1054           GetOptions ("help|?");    # -help and -? will both set $opt_help
1055
1056       Other characters that can't appear in Perl identifiers are also
1057       supported as aliases with Getopt::Long of at least version 2.39.
1058
1059       As of version 2.32 Getopt::Long provides auto-help, a quick and easy
1060       way to add the options --help and -? to your program, and handle them.
1061
1062       See "auto_help" in section "Configuring Getopt::Long".
1063

AUTHOR

1065       Johan Vromans <jvromans@squirrel.nl>
1066
1068       This program is Copyright 1990,2013 by Johan Vromans.  This program is
1069       free software; you can redistribute it and/or modify it under the terms
1070       of the Perl Artistic License or the GNU General Public License as
1071       published by the Free Software Foundation; either version 2 of the
1072       License, or (at your option) any later version.
1073
1074       This program is distributed in the hope that it will be useful, but
1075       WITHOUT ANY WARRANTY; without even the implied warranty of
1076       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1077       General Public License for more details.
1078
1079       If you do not have a copy of the GNU General Public License write to
1080       the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
1081       USA.
1082
1083
1084
1085perl v5.16.3                      2013-06-16                   Getopt::Long(3)
Impressum