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       (If both "--verbose" and "--noverbose" are given, whichever is given
134       last takes precedence.)
135
136       An incremental option is specified with a plus "+" after the option
137       name:
138
139           my $verbose = '';   # option variable with default value (false)
140           GetOptions ('verbose+' => \$verbose);
141
142       Using "--verbose" on the command line will increment the value of
143       $verbose. This way the program can keep track of how many times the
144       option occurred on the command line. For example, each occurrence of
145       "--verbose" could increase the verbosity level of the program.
146
147   Mixing command line option with other arguments
148       Usually programs take command line options as well as other arguments,
149       for example, file names. It is good practice to always specify the
150       options first, and the other arguments last. Getopt::Long will,
151       however, allow the options and arguments to be mixed and 'filter out'
152       all the options before passing the rest of the arguments to the
153       program. To stop Getopt::Long from processing further arguments, insert
154       a double dash "--" on the command line:
155
156           --size 24 -- --all
157
158       In this example, "--all" will not be treated as an option, but passed
159       to the program unharmed, in @ARGV.
160
161   Options with values
162       For options that take values it must be specified whether the option
163       value is required or not, and what kind of value the option expects.
164
165       Three kinds of values are supported: integer numbers, floating point
166       numbers, and strings.
167
168       If the option value is required, Getopt::Long will take the command
169       line argument that follows the option and assign this to the option
170       variable. If, however, the option value is specified as optional, this
171       will only be done if that value does not look like a valid command line
172       option itself.
173
174           my $tag = '';       # option variable with default value
175           GetOptions ('tag=s' => \$tag);
176
177       In the option specification, the option name is followed by an equals
178       sign "=" and the letter "s". The equals sign indicates that this option
179       requires a value. The letter "s" indicates that this value is an
180       arbitrary string. Other possible value types are "i" for integer
181       values, and "f" for floating point values. Using a colon ":" instead of
182       the equals sign indicates that the option value is optional. In this
183       case, if no suitable value is supplied, string valued options get an
184       empty string '' assigned, while numeric options are set to 0.
185
186       (If the same option appears more than once on the command line, the
187       last given value is used.  If you want to take all the values, see
188       below.)
189
190   Options with multiple values
191       Options sometimes take several values. For example, a program could use
192       multiple directories to search for library files:
193
194           --library lib/stdlib --library lib/extlib
195
196       To accomplish this behaviour, simply specify an array reference as the
197       destination for the option:
198
199           GetOptions ("library=s" => \@libfiles);
200
201       Alternatively, you can specify that the option can have multiple values
202       by adding a "@", and pass a reference to a scalar as the destination:
203
204           GetOptions ("library=s@" => \$libfiles);
205
206       Used with the example above, @libfiles c.q. @$libfiles would contain
207       two strings upon completion: "lib/stdlib" and "lib/extlib", in that
208       order. It is also possible to specify that only integer or floating
209       point numbers are acceptable values.
210
211       Often it is useful to allow comma-separated lists of values as well as
212       multiple occurrences of the options. This is easy using Perl's split()
213       and join() operators:
214
215           GetOptions ("library=s" => \@libfiles);
216           @libfiles = split(/,/,join(',',@libfiles));
217
218       Of course, it is important to choose the right separator string for
219       each purpose.
220
221       Warning: What follows is an experimental feature.
222
223       Options can take multiple values at once, for example
224
225           --coordinates 52.2 16.4 --rgbcolor 255 255 149
226
227       This can be accomplished by adding a repeat specifier to the option
228       specification. Repeat specifiers are very similar to the "{...}" repeat
229       specifiers that can be used with regular expression patterns.  For
230       example, the above command line would be handled as follows:
231
232           GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);
233
234       The destination for the option must be an array or array reference.
235
236       It is also possible to specify the minimal and maximal number of
237       arguments an option takes. "foo=s{2,4}" indicates an option that takes
238       at least two and at most 4 arguments. "foo=s{1,}" indicates one or more
239       values; "foo:s{,}" indicates zero or more option values.
240
241   Options with hash values
242       If the option destination is a reference to a hash, the option will
243       take, as value, strings of the form key"="value. The value will be
244       stored with the specified key in the hash.
245
246           GetOptions ("define=s" => \%defines);
247
248       Alternatively you can use:
249
250           GetOptions ("define=s%" => \$defines);
251
252       When used with command line options:
253
254           --define os=linux --define vendor=redhat
255
256       the hash %defines (or %$defines) will contain two keys, "os" with value
257       "linux" and "vendor" with value "redhat". It is also possible to
258       specify that only integer or floating point numbers are acceptable
259       values. The keys are always taken to be strings.
260
261   User-defined subroutines to handle options
262       Ultimate control over what should be done when (actually: each time) an
263       option is encountered on the command line can be achieved by
264       designating a reference to a subroutine (or an anonymous subroutine) as
265       the option destination. When GetOptions() encounters the option, it
266       will call the subroutine with two or three arguments. The first
267       argument is the name of the option. (Actually, it is an object that
268       stringifies to the name of the option.) For a scalar or array
269       destination, the second argument is the value to be stored. For a hash
270       destination, the second argument is the key to the hash, and the third
271       argument the value to be stored. It is up to the subroutine to store
272       the value, or do whatever it thinks is appropriate.
273
274       A trivial application of this mechanism is to implement options that
275       are related to each other. For example:
276
277           my $verbose = '';   # option variable with default value (false)
278           GetOptions ('verbose' => \$verbose,
279                       'quiet'   => sub { $verbose = 0 });
280
281       Here "--verbose" and "--quiet" control the same variable $verbose, but
282       with opposite values.
283
284       If the subroutine needs to signal an error, it should call die() with
285       the desired error message as its argument. GetOptions() will catch the
286       die(), issue the error message, and record that an error result must be
287       returned upon completion.
288
289       If the text of the error message starts with an exclamation mark "!"
290       it is interpreted specially by GetOptions(). There is currently one
291       special command implemented: die("!FINISH") will cause GetOptions() to
292       stop processing options, as if it encountered a double dash "--".
293
294       Here is an example of how to access the option name and value from
295       within a subroutine:
296
297           GetOptions ('opt=i' => \&handler);
298           sub handler {
299               my ($opt_name, $opt_value) = @_;
300               print("Option name is $opt_name and value is $opt_value\n");
301           }
302
303   Options with multiple names
304       Often it is user friendly to supply alternate mnemonic names for
305       options. For example "--height" could be an alternate name for
306       "--length". Alternate names can be included in the option
307       specification, separated by vertical bar "|" characters. To implement
308       the above example:
309
310           GetOptions ('length|height=f' => \$length);
311
312       The first name is called the primary name, the other names are called
313       aliases. When using a hash to store options, the key will always be the
314       primary name.
315
316       Multiple alternate names are possible.
317
318   Case and abbreviations
319       Without additional configuration, GetOptions() will ignore the case of
320       option names, and allow the options to be abbreviated to uniqueness.
321
322           GetOptions ('length|height=f' => \$length, "head" => \$head);
323
324       This call will allow "--l" and "--L" for the length option, but
325       requires a least "--hea" and "--hei" for the head and height options.
326
327   Summary of Option Specifications
328       Each option specifier consists of two parts: the name specification and
329       the argument specification.
330
331       The name specification contains the name of the option, optionally
332       followed by a list of alternative names separated by vertical bar
333       characters.
334
335           length            option name is "length"
336           length|size|l     name is "length", aliases are "size" and "l"
337
338       The argument specification is optional. If omitted, the option is
339       considered boolean, a value of 1 will be assigned when the option is
340       used on the command line.
341
342       The argument specification can be
343
344       !   The option does not take an argument and may be negated by
345           prefixing it with "no" or "no-". E.g. "foo!" will allow "--foo" (a
346           value of 1 will be assigned) as well as "--nofoo" and "--no-foo" (a
347           value of 0 will be assigned). If the option has aliases, this
348           applies to the aliases as well.
349
350           Using negation on a single letter option when bundling is in effect
351           is pointless and will result in a warning.
352
353       +   The option does not take an argument and will be incremented by 1
354           every time it appears on the command line. E.g. "more+", when used
355           with "--more --more --more", will increment the value three times,
356           resulting in a value of 3 (provided it was 0 or undefined at
357           first).
358
359           The "+" specifier is ignored if the option destination is not a
360           scalar.
361
362       = type [ desttype ] [ repeat ]
363           The option requires an argument of the given type. Supported types
364           are:
365
366           s   String. An arbitrary sequence of characters. It is valid for
367               the argument to start with "-" or "--".
368
369           i   Integer. An optional leading plus or minus sign, followed by a
370               sequence of digits.
371
372           o   Extended integer, Perl style. This can be either an optional
373               leading plus or minus sign, followed by a sequence of digits,
374               or an octal string (a zero, optionally followed by '0', '1', ..
375               '7'), or a hexadecimal string ("0x" followed by '0' .. '9', 'a'
376               .. 'f', case insensitive), or a binary string ("0b" followed by
377               a series of '0' and '1').
378
379           f   Real number. For example 3.14, -6.23E24 and so on.
380
381           The desttype can be "@" or "%" to specify that the option is list
382           or a hash valued. This is only needed when the destination for the
383           option value is not otherwise specified. It should be omitted when
384           not needed.
385
386           The repeat specifies the number of values this option takes per
387           occurrence on the command line. It has the format "{" [ min ] [ ","
388           [ max ] ] "}".
389
390           min denotes the minimal number of arguments. It defaults to 1 for
391           options with "=" and to 0 for options with ":", see below. Note
392           that min overrules the "=" / ":" semantics.
393
394           max denotes the maximum number of arguments. It must be at least
395           min. If max is omitted, but the comma is not, there is no upper
396           bound to the number of argument values taken.
397
398       : type [ desttype ]
399           Like "=", but designates the argument as optional.  If omitted, an
400           empty string will be assigned to string values options, and the
401           value zero to numeric options.
402
403           Note that if a string argument starts with "-" or "--", it will be
404           considered an option on itself.
405
406       : number [ desttype ]
407           Like ":i", but if the value is omitted, the number will be
408           assigned.
409
410           If the number is octal, hexadecimal or binary, behaves like ":o".
411
412       : + [ desttype ]
413           Like ":i", but if the value is omitted, the current value for the
414           option will be incremented.
415

Advanced Possibilities

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

Configuring Getopt::Long

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

Exportable Methods

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

Return values and Errors

967       Configuration errors and errors in the option definitions are signalled
968       using die() and will terminate the calling program unless the call to
969       Getopt::Long::GetOptions() was embedded in "eval { ...  }", or die()
970       was trapped using $SIG{__DIE__}.
971
972       GetOptions returns true to indicate success.  It returns false when the
973       function detected one or more errors during option parsing. These
974       errors are signalled using warn() and can be trapped with
975       $SIG{__WARN__}.
976

Legacy

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

Tips and Techniques

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

Troubleshooting

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

AUTHOR

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