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

Advanced Possibilities

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

Configuring Getopt::Long

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

Exportable Methods

904       VersionMessage
905           This subroutine provides a standard version message. Its argument
906           can be:
907
908           ·   A string containing the text of a message to print before
909               printing the standard message.
910
911           ·   A numeric value corresponding to the desired exit status.
912
913           ·   A reference to a hash.
914
915           If more than one argument is given then the entire argument list is
916           assumed to be a hash.  If a hash is supplied (either as a reference
917           or as a list) it should contain one or more elements with the
918           following keys:
919
920           "-message"
921           "-msg"
922               The text of a message to print immediately prior to printing
923               the program's usage message.
924
925           "-exitval"
926               The desired exit status to pass to the exit() function.  This
927               should be an integer, or else the string "NOEXIT" to indicate
928               that control should simply be returned without terminating the
929               invoking process.
930
931           "-output"
932               A reference to a filehandle, or the pathname of a file to which
933               the usage message should be written. The default is "\*STDERR"
934               unless the exit value is less than 2 (in which case the default
935               is "\*STDOUT").
936
937           You cannot tie this routine directly to an option, e.g.:
938
939               GetOptions("version" => \&VersionMessage);
940
941           Use this instead:
942
943               GetOptions("version" => sub { VersionMessage() });
944
945       HelpMessage
946           This subroutine produces a standard help message, derived from the
947           program's POD section SYNOPSIS using Pod::Usage. It takes the same
948           arguments as VersionMessage(). In particular, you cannot tie it
949           directly to an option, e.g.:
950
951               GetOptions("help" => \&HelpMessage);
952
953           Use this instead:
954
955               GetOptions("help" => sub { HelpMessage() });
956

Return values and Errors

958       Configuration errors and errors in the option definitions are signalled
959       using die() and will terminate the calling program unless the call to
960       Getopt::Long::GetOptions() was embedded in "eval { ...  }", or die()
961       was trapped using $SIG{__DIE__}.
962
963       GetOptions returns true to indicate success.  It returns false when the
964       function detected one or more errors during option parsing. These
965       errors are signalled using warn() and can be trapped with
966       $SIG{__WARN__}.
967

Legacy

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

Tips and Techniques

1028   Pushing multiple values in a hash option
1029       Sometimes you want to combine the best of hashes and arrays. For
1030       example, the command line:
1031
1032         --list add=first --list add=second --list add=third
1033
1034       where each successive 'list add' option will push the value of add into
1035       array ref $list->{'add'}. The result would be like
1036
1037         $list->{add} = [qw(first second third)];
1038
1039       This can be accomplished with a destination routine:
1040
1041         GetOptions('list=s%' =>
1042                      sub { push(@{$list{$_[1]}}, $_[2]) });
1043

Troubleshooting

1045   GetOptions does not return a false result when an option is not supplied
1046       That's why they're called 'options'.
1047
1048   GetOptions does not split the command line correctly
1049       The command line is not split by GetOptions, but by the command line
1050       interpreter (CLI). On Unix, this is the shell. On Windows, it is
1051       COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
1052
1053       It is important to know that these CLIs may behave different when the
1054       command line contains special characters, in particular quotes or
1055       backslashes. For example, with Unix shells you can use single quotes
1056       ("'") and double quotes (""") to group words together. The following
1057       alternatives are equivalent on Unix:
1058
1059           "two words"
1060           'two words'
1061           two\ words
1062
1063       In case of doubt, insert the following statement in front of your Perl
1064       program:
1065
1066           print STDERR (join("|",@ARGV),"\n");
1067
1068       to verify how your CLI passes the arguments to the program.
1069
1070   Undefined subroutine &main::GetOptions called
1071       Are you running Windows, and did you write
1072
1073           use GetOpt::Long;
1074
1075       (note the capital 'O')?
1076
1077   How do I put a "-?" option into a Getopt::Long?
1078       You can only obtain this using an alias, and Getopt::Long of at least
1079       version 2.13.
1080
1081           use Getopt::Long;
1082           GetOptions ("help|?");    # -help and -? will both set $opt_help
1083
1084       Other characters that can't appear in Perl identifiers are also
1085       supported in aliases with Getopt::Long of at version 2.39. Note that
1086       the characters "!", "|", "+", "=", and ":" can only appear as the first
1087       (or only) character of an alias.
1088
1089       As of version 2.32 Getopt::Long provides auto-help, a quick and easy
1090       way to add the options --help and -? to your program, and handle them.
1091
1092       See "auto_help" in section "Configuring Getopt::Long".
1093

AUTHOR

1095       Johan Vromans <jvromans@squirrel.nl>
1096
1098       This program is Copyright 1990,2015 by Johan Vromans.  This program is
1099       free software; you can redistribute it and/or modify it under the terms
1100       of the Perl Artistic License or the GNU General Public License as
1101       published by the Free Software Foundation; either version 2 of the
1102       License, or (at your option) any later version.
1103
1104       This program is distributed in the hope that it will be useful, but
1105       WITHOUT ANY WARRANTY; without even the implied warranty of
1106       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1107       General Public License for more details.
1108
1109       If you do not have a copy of the GNU General Public License write to
1110       the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
1111       USA.
1112
1113
1114
1115perl v5.32.0                      2020-08-18                   Getopt::Long(3)
Impressum