1Getopt::Long(3) User Contributed Perl Documentation Getopt::Long(3)
2
3
4
6 Getopt::Long - Extended processing of command line options
7
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
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
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
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 In version 2.37 the first argument to the callback function was changed
288 from string to object. This was done to make room for extensions and
289 more detailed control. The object stringifies to the option name so
290 this change should not introduce compatibility problems.
291
292 Here is an example of how to access the option name and value from
293 within a subroutine:
294
295 GetOptions ('opt=i' => \&handler);
296 sub handler {
297 my ($opt_name, $opt_value) = @_;
298 print("Option name is $opt_name and value is $opt_value\n");
299 }
300
301 Options with multiple names
302 Often it is user friendly to supply alternate mnemonic names for
303 options. For example "--height" could be an alternate name for
304 "--length". Alternate names can be included in the option
305 specification, separated by vertical bar "|" characters. To implement
306 the above example:
307
308 GetOptions ('length|height=f' => \$length);
309
310 The first name is called the primary name, the other names are called
311 aliases. When using a hash to store options, the key will always be the
312 primary name.
313
314 Multiple alternate names are possible.
315
316 Case and abbreviations
317 Without additional configuration, GetOptions() will ignore the case of
318 option names, and allow the options to be abbreviated to uniqueness.
319
320 GetOptions ('length|height=f' => \$length, "head" => \$head);
321
322 This call will allow "--l" and "--L" for the length option, but
323 requires a least "--hea" and "--hei" for the head and height options.
324
325 Summary of Option Specifications
326 Each option specifier consists of two parts: the name specification and
327 the argument specification.
328
329 The name specification contains the name of the option, optionally
330 followed by a list of alternative names separated by vertical bar
331 characters.
332
333 length option name is "length"
334 length|size|l name is "length", aliases are "size" and "l"
335
336 The argument specification is optional. If omitted, the option is
337 considered boolean, a value of 1 will be assigned when the option is
338 used on the command line.
339
340 The argument specification can be
341
342 ! The option does not take an argument and may be negated by
343 prefixing it with "no" or "no-". E.g. "foo!" will allow "--foo" (a
344 value of 1 will be assigned) as well as "--nofoo" and "--no-foo" (a
345 value of 0 will be assigned). If the option has aliases, this
346 applies to the aliases as well.
347
348 Using negation on a single letter option when bundling is in effect
349 is pointless and will result in a warning.
350
351 + The option does not take an argument and will be incremented by 1
352 every time it appears on the command line. E.g. "more+", when used
353 with "--more --more --more", will increment the value three times,
354 resulting in a value of 3 (provided it was 0 or undefined at
355 first).
356
357 The "+" specifier is ignored if the option destination is not a
358 scalar.
359
360 = type [ desttype ] [ repeat ]
361 The option requires an argument of the given type. Supported types
362 are:
363
364 s String. An arbitrary sequence of characters. It is valid for
365 the argument to start with "-" or "--".
366
367 i Integer. An optional leading plus or minus sign, followed by a
368 sequence of digits.
369
370 o Extended integer, Perl style. This can be either an optional
371 leading plus or minus sign, followed by a sequence of digits,
372 or an octal string (a zero, optionally followed by '0', '1', ..
373 '7'), or a hexadecimal string ("0x" followed by '0' .. '9', 'a'
374 .. 'f', case insensitive), or a binary string ("0b" followed by
375 a series of '0' and '1').
376
377 f Real number. For example 3.14, "-6.23E24" and so on.
378
379 The desttype can be "@" or "%" to specify that the option is list
380 or a hash valued. This is only needed when the destination for the
381 option value is not otherwise specified. It should be omitted when
382 not needed.
383
384 The repeat specifies the number of values this option takes per
385 occurrence on the command line. It has the format "{" [ min ] [ ","
386 [ max ] ] "}".
387
388 min denotes the minimal number of arguments. It defaults to 1 for
389 options with "=" and to 0 for options with ":", see below. Note
390 that min overrules the "=" / ":" semantics.
391
392 max denotes the maximum number of arguments. It must be at least
393 min. If max is omitted, but the comma is not, there is no upper
394 bound to the number of argument values taken.
395
396 : type [ desttype ]
397 Like "=", but designates the argument as optional. If omitted, an
398 empty string will be assigned to string values options, and the
399 value zero to numeric options.
400
401 Note that if a string argument starts with "-" or "--", it will be
402 considered an option on itself.
403
404 : number [ desttype ]
405 Like ":i", but if the value is omitted, the number will be
406 assigned.
407
408 : + [ desttype ]
409 Like ":i", but if the value is omitted, the current value for the
410 option will be incremented.
411
413 Object oriented interface
414 Getopt::Long can be used in an object oriented way as well:
415
416 use Getopt::Long;
417 $p = Getopt::Long::Parser->new;
418 $p->configure(...configuration options...);
419 if ($p->getoptions(...options descriptions...)) ...
420 if ($p->getoptionsfromarray( \@array, ...options descriptions...)) ...
421
422 Configuration options can be passed to the constructor:
423
424 $p = new Getopt::Long::Parser
425 config => [...configuration options...];
426
427 Thread Safety
428 Getopt::Long is thread safe when using ithreads as of Perl 5.8. It is
429 not thread safe when using the older (experimental and now obsolete)
430 threads implementation that was added to Perl 5.005.
431
432 Documentation and help texts
433 Getopt::Long encourages the use of Pod::Usage to produce help messages.
434 For example:
435
436 use Getopt::Long;
437 use Pod::Usage;
438
439 my $man = 0;
440 my $help = 0;
441
442 GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
443 pod2usage(1) if $help;
444 pod2usage(-exitval => 0, -verbose => 2) if $man;
445
446 __END__
447
448 =head1 NAME
449
450 sample - Using Getopt::Long and Pod::Usage
451
452 =head1 SYNOPSIS
453
454 sample [options] [file ...]
455
456 Options:
457 -help brief help message
458 -man full documentation
459
460 =head1 OPTIONS
461
462 =over 8
463
464 =item B<-help>
465
466 Print a brief help message and exits.
467
468 =item B<-man>
469
470 Prints the manual page and exits.
471
472 =back
473
474 =head1 DESCRIPTION
475
476 B<This program> will read the given input file(s) and do something
477 useful with the contents thereof.
478
479 =cut
480
481 See Pod::Usage for details.
482
483 Parsing options from an arbitrary array
484 By default, GetOptions parses the options that are present in the
485 global array @ARGV. A special entry "GetOptionsFromArray" can be used
486 to parse options from an arbitrary array.
487
488 use Getopt::Long qw(GetOptionsFromArray);
489 $ret = GetOptionsFromArray(\@myopts, ...);
490
491 When used like this, options and their possible values are removed from
492 @myopts, the global @ARGV is not touched at all.
493
494 The following two calls behave identically:
495
496 $ret = GetOptions( ... );
497 $ret = GetOptionsFromArray(\@ARGV, ... );
498
499 This also means that a first argument hash reference now becomes the
500 second argument:
501
502 $ret = GetOptions(\%opts, ... );
503 $ret = GetOptionsFromArray(\@ARGV, \%opts, ... );
504
505 Parsing options from an arbitrary string
506 A special entry "GetOptionsFromString" can be used to parse options
507 from an arbitrary string.
508
509 use Getopt::Long qw(GetOptionsFromString);
510 $ret = GetOptionsFromString($string, ...);
511
512 The contents of the string are split into arguments using a call to
513 "Text::ParseWords::shellwords". As with "GetOptionsFromArray", the
514 global @ARGV is not touched.
515
516 It is possible that, upon completion, not all arguments in the string
517 have been processed. "GetOptionsFromString" will, when called in list
518 context, return both the return status and an array reference to any
519 remaining arguments:
520
521 ($ret, $args) = GetOptionsFromString($string, ... );
522
523 If any arguments remain, and "GetOptionsFromString" was not called in
524 list context, a message will be given and "GetOptionsFromString" will
525 return failure.
526
527 As with GetOptionsFromArray, a first argument hash reference now
528 becomes the second argument.
529
530 Storing options values in a hash
531 Sometimes, for example when there are a lot of options, having a
532 separate variable for each of them can be cumbersome. GetOptions()
533 supports, as an alternative mechanism, storing options values in a
534 hash.
535
536 To obtain this, a reference to a hash must be passed as the first
537 argument to GetOptions(). For each option that is specified on the
538 command line, the option value will be stored in the hash with the
539 option name as key. Options that are not actually used on the command
540 line will not be put in the hash, on other words, "exists($h{option})"
541 (or defined()) can be used to test if an option was used. The drawback
542 is that warnings will be issued if the program runs under "use strict"
543 and uses $h{option} without testing with exists() or defined() first.
544
545 my %h = ();
546 GetOptions (\%h, 'length=i'); # will store in $h{length}
547
548 For options that take list or hash values, it is necessary to indicate
549 this by appending an "@" or "%" sign after the type:
550
551 GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
552
553 To make things more complicated, the hash may contain references to the
554 actual destinations, for example:
555
556 my $len = 0;
557 my %h = ('length' => \$len);
558 GetOptions (\%h, 'length=i'); # will store in $len
559
560 This example is fully equivalent with:
561
562 my $len = 0;
563 GetOptions ('length=i' => \$len); # will store in $len
564
565 Any mixture is possible. For example, the most frequently used options
566 could be stored in variables while all other options get stored in the
567 hash:
568
569 my $verbose = 0; # frequently referred
570 my $debug = 0; # frequently referred
571 my %h = ('verbose' => \$verbose, 'debug' => \$debug);
572 GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
573 if ( $verbose ) { ... }
574 if ( exists $h{filter} ) { ... option 'filter' was specified ... }
575
576 Bundling
577 With bundling it is possible to set several single-character options at
578 once. For example if "a", "v" and "x" are all valid options,
579
580 -vax
581
582 will set all three.
583
584 Getopt::Long supports three styles of bundling. To enable bundling, a
585 call to Getopt::Long::Configure is required.
586
587 The simplest style of bundling can be enabled with:
588
589 Getopt::Long::Configure ("bundling");
590
591 Configured this way, single-character options can be bundled but long
592 options must always start with a double dash "--" to avoid ambiguity.
593 For example, when "vax", "a", "v" and "x" are all valid options,
594
595 -vax
596
597 will set "a", "v" and "x", but
598
599 --vax
600
601 will set "vax".
602
603 The second style of bundling lifts this restriction. It can be enabled
604 with:
605
606 Getopt::Long::Configure ("bundling_override");
607
608 Now, "-vax" will set the option "vax".
609
610 In all of the above cases, option values may be inserted in the bundle.
611 For example:
612
613 -h24w80
614
615 is equivalent to
616
617 -h 24 -w 80
618
619 A third style of bundling allows only values to be bundled with
620 options. It can be enabled with:
621
622 Getopt::Long::Configure ("bundling_values");
623
624 Now, "-h24" will set the option "h" to 24, but option bundles like
625 "-vxa" and "-h24w80" are flagged as errors.
626
627 Enabling "bundling_values" will disable the other two styles of
628 bundling.
629
630 When configured for bundling, single-character options are matched case
631 sensitive while long options are matched case insensitive. To have the
632 single-character options matched case insensitive as well, use:
633
634 Getopt::Long::Configure ("bundling", "ignorecase_always");
635
636 It goes without saying that bundling can be quite confusing.
637
638 The lonesome dash
639 Normally, a lone dash "-" on the command line will not be considered an
640 option. Option processing will terminate (unless "permute" is
641 configured) and the dash will be left in @ARGV.
642
643 It is possible to get special treatment for a lone dash. This can be
644 achieved by adding an option specification with an empty name, for
645 example:
646
647 GetOptions ('' => \$stdio);
648
649 A lone dash on the command line will now be a legal option, and using
650 it will set variable $stdio.
651
652 Argument callback
653 A special option 'name' "<>" can be used to designate a subroutine to
654 handle non-option arguments. When GetOptions() encounters an argument
655 that does not look like an option, it will immediately call this
656 subroutine and passes it one parameter: the argument name. Well,
657 actually it is an object that stringifies to the argument name.
658
659 For example:
660
661 my $width = 80;
662 sub process { ... }
663 GetOptions ('width=i' => \$width, '<>' => \&process);
664
665 When applied to the following command line:
666
667 arg1 --width=72 arg2 --width=60 arg3
668
669 This will call "process("arg1")" while $width is 80, "process("arg2")"
670 while $width is 72, and "process("arg3")" while $width is 60.
671
672 This feature requires configuration option permute, see section
673 "Configuring Getopt::Long".
674
676 Getopt::Long can be configured by calling subroutine
677 Getopt::Long::Configure(). This subroutine takes a list of quoted
678 strings, each specifying a configuration option to be enabled, e.g.
679 "ignore_case", or disabled, e.g. "no_ignore_case". Case does not
680 matter. Multiple calls to Configure() are possible.
681
682 Alternatively, as of version 2.24, the configuration options may be
683 passed together with the "use" statement:
684
685 use Getopt::Long qw(:config no_ignore_case bundling);
686
687 The following options are available:
688
689 default This option causes all configuration options to be reset to
690 their default values.
691
692 posix_default
693 This option causes all configuration options to be reset to
694 their default values as if the environment variable
695 POSIXLY_CORRECT had been set.
696
697 auto_abbrev Allow option names to be abbreviated to uniqueness.
698 Default is enabled unless environment variable
699 POSIXLY_CORRECT has been set, in which case "auto_abbrev"
700 is disabled.
701
702 getopt_compat
703 Allow "+" to start options. Default is enabled unless
704 environment variable POSIXLY_CORRECT has been set, in which
705 case "getopt_compat" is disabled.
706
707 gnu_compat "gnu_compat" controls whether "--opt=" is allowed, and what
708 it should do. Without "gnu_compat", "--opt=" gives an
709 error. With "gnu_compat", "--opt=" will give option "opt"
710 and empty value. This is the way GNU getopt_long() does
711 it.
712
713 Note that "--opt value" is still accepted, even though GNU
714 getopt_long() doesn't.
715
716 gnu_getopt This is a short way of setting "gnu_compat" "bundling"
717 "permute" "no_getopt_compat". With "gnu_getopt", command
718 line handling should be reasonably compatible with GNU
719 getopt_long().
720
721 require_order
722 Whether command line arguments are allowed to be mixed with
723 options. Default is disabled unless environment variable
724 POSIXLY_CORRECT has been set, in which case "require_order"
725 is enabled.
726
727 See also "permute", which is the opposite of
728 "require_order".
729
730 permute Whether command line arguments are allowed to be mixed with
731 options. Default is enabled unless environment variable
732 POSIXLY_CORRECT has been set, in which case "permute" is
733 disabled. Note that "permute" is the opposite of
734 "require_order".
735
736 If "permute" is enabled, this means that
737
738 --foo arg1 --bar arg2 arg3
739
740 is equivalent to
741
742 --foo --bar arg1 arg2 arg3
743
744 If an argument callback routine is specified, @ARGV will
745 always be empty upon successful return of GetOptions()
746 since all options have been processed. The only exception
747 is when "--" is used:
748
749 --foo arg1 --bar arg2 -- arg3
750
751 This will call the callback routine for arg1 and arg2, and
752 then terminate GetOptions() leaving "arg3" in @ARGV.
753
754 If "require_order" is enabled, options processing
755 terminates when the first non-option is encountered.
756
757 --foo arg1 --bar arg2 arg3
758
759 is equivalent to
760
761 --foo -- arg1 --bar arg2 arg3
762
763 If "pass_through" is also enabled, options processing will
764 terminate at the first unrecognized option, or non-option,
765 whichever comes first.
766
767 bundling (default: disabled)
768 Enabling this option will allow single-character options to
769 be bundled. To distinguish bundles from long option names,
770 long options must be introduced with "--" and bundles with
771 "-".
772
773 Note that, if you have options "a", "l" and "all", and
774 auto_abbrev enabled, possible arguments and option settings
775 are:
776
777 using argument sets option(s)
778 ------------------------------------------
779 -a, --a a
780 -l, --l l
781 -al, -la, -ala, -all,... a, l
782 --al, --all all
783
784 The surprising part is that "--a" sets option "a" (due to
785 auto completion), not "all".
786
787 Note: disabling "bundling" also disables
788 "bundling_override".
789
790 bundling_override (default: disabled)
791 If "bundling_override" is enabled, bundling is enabled as
792 with "bundling" but now long option names override option
793 bundles.
794
795 Note: disabling "bundling_override" also disables
796 "bundling".
797
798 Note: Using option bundling can easily lead to unexpected
799 results, especially when mixing long options and bundles.
800 Caveat emptor.
801
802 ignore_case (default: enabled)
803 If enabled, case is ignored when matching option names. If,
804 however, bundling is enabled as well, single character
805 options will be treated case-sensitive.
806
807 With "ignore_case", option specifications for options that
808 only differ in case, e.g., "foo" and "Foo", will be flagged
809 as duplicates.
810
811 Note: disabling "ignore_case" also disables
812 "ignore_case_always".
813
814 ignore_case_always (default: disabled)
815 When bundling is in effect, case is ignored on single-
816 character options also.
817
818 Note: disabling "ignore_case_always" also disables
819 "ignore_case".
820
821 auto_version (default:disabled)
822 Automatically provide support for the --version option if
823 the application did not specify a handler for this option
824 itself.
825
826 Getopt::Long will provide a standard version message that
827 includes the program name, its version (if $main::VERSION
828 is defined), and the versions of Getopt::Long and Perl. The
829 message will be written to standard output and processing
830 will terminate.
831
832 "auto_version" will be enabled if the calling program
833 explicitly specified a version number higher than 2.32 in
834 the "use" or "require" statement.
835
836 auto_help (default:disabled)
837 Automatically provide support for the --help and -? options
838 if the application did not specify a handler for this
839 option itself.
840
841 Getopt::Long will provide a help message using module
842 Pod::Usage. The message, derived from the SYNOPSIS POD
843 section, will be written to standard output and processing
844 will terminate.
845
846 "auto_help" will be enabled if the calling program
847 explicitly specified a version number higher than 2.32 in
848 the "use" or "require" statement.
849
850 pass_through (default: disabled)
851 With "pass_through" anything that is unknown, ambiguous or
852 supplied with an invalid option will not be flagged as an
853 error. Instead the unknown option(s) will be passed to the
854 catchall "<>" if present, otherwise through to @ARGV. This
855 makes it possible to write wrapper scripts that process
856 only part of the user supplied command line arguments, and
857 pass the remaining options to some other program.
858
859 If "require_order" is enabled, options processing will
860 terminate at the first unrecognized option, or non-option,
861 whichever comes first and all remaining arguments are
862 passed to @ARGV instead of the catchall "<>" if present.
863 However, if "permute" is enabled instead, results can
864 become confusing.
865
866 Note that the options terminator (default "--"), if
867 present, will also be passed through in @ARGV.
868
869 prefix The string that starts options. If a constant string is not
870 sufficient, see "prefix_pattern".
871
872 prefix_pattern
873 A Perl pattern that identifies the strings that introduce
874 options. Default is "--|-|\+" unless environment variable
875 POSIXLY_CORRECT has been set, in which case it is "--|-".
876
877 long_prefix_pattern
878 A Perl pattern that allows the disambiguation of long and
879 short prefixes. Default is "--".
880
881 Typically you only need to set this if you are using
882 nonstandard prefixes and want some or all of them to have
883 the same semantics as '--' does under normal circumstances.
884
885 For example, setting prefix_pattern to "--|-|\+|\/" and
886 long_prefix_pattern to "--|\/" would add Win32 style
887 argument handling.
888
889 debug (default: disabled)
890 Enable debugging output.
891
893 VersionMessage
894 This subroutine provides a standard version message. Its argument
895 can be:
896
897 · A string containing the text of a message to print before
898 printing the standard message.
899
900 · A numeric value corresponding to the desired exit status.
901
902 · A reference to a hash.
903
904 If more than one argument is given then the entire argument list is
905 assumed to be a hash. If a hash is supplied (either as a reference
906 or as a list) it should contain one or more elements with the
907 following keys:
908
909 "-message"
910 "-msg"
911 The text of a message to print immediately prior to printing
912 the program's usage message.
913
914 "-exitval"
915 The desired exit status to pass to the exit() function. This
916 should be an integer, or else the string "NOEXIT" to indicate
917 that control should simply be returned without terminating the
918 invoking process.
919
920 "-output"
921 A reference to a filehandle, or the pathname of a file to which
922 the usage message should be written. The default is "\*STDERR"
923 unless the exit value is less than 2 (in which case the default
924 is "\*STDOUT").
925
926 You cannot tie this routine directly to an option, e.g.:
927
928 GetOptions("version" => \&VersionMessage);
929
930 Use this instead:
931
932 GetOptions("version" => sub { VersionMessage() });
933
934 HelpMessage
935 This subroutine produces a standard help message, derived from the
936 program's POD section SYNOPSIS using Pod::Usage. It takes the same
937 arguments as VersionMessage(). In particular, you cannot tie it
938 directly to an option, e.g.:
939
940 GetOptions("help" => \&HelpMessage);
941
942 Use this instead:
943
944 GetOptions("help" => sub { HelpMessage() });
945
947 Configuration errors and errors in the option definitions are signalled
948 using die() and will terminate the calling program unless the call to
949 Getopt::Long::GetOptions() was embedded in "eval { ... }", or die()
950 was trapped using $SIG{__DIE__}.
951
952 GetOptions returns true to indicate success. It returns false when the
953 function detected one or more errors during option parsing. These
954 errors are signalled using warn() and can be trapped with
955 $SIG{__WARN__}.
956
958 The earliest development of "newgetopt.pl" started in 1990, with Perl
959 version 4. As a result, its development, and the development of
960 Getopt::Long, has gone through several stages. Since backward
961 compatibility has always been extremely important, the current version
962 of Getopt::Long still supports a lot of constructs that nowadays are no
963 longer necessary or otherwise unwanted. This section describes briefly
964 some of these 'features'.
965
966 Default destinations
967 When no destination is specified for an option, GetOptions will store
968 the resultant value in a global variable named "opt_"XXX, where XXX is
969 the primary name of this option. When a program executes under "use
970 strict" (recommended), these variables must be pre-declared with our()
971 or "use vars".
972
973 our $opt_length = 0;
974 GetOptions ('length=i'); # will store in $opt_length
975
976 To yield a usable Perl variable, characters that are not part of the
977 syntax for variables are translated to underscores. For example,
978 "--fpp-struct-return" will set the variable $opt_fpp_struct_return.
979 Note that this variable resides in the namespace of the calling
980 program, not necessarily "main". For example:
981
982 GetOptions ("size=i", "sizes=i@");
983
984 with command line "-size 10 -sizes 24 -sizes 48" will perform the
985 equivalent of the assignments
986
987 $opt_size = 10;
988 @opt_sizes = (24, 48);
989
990 Alternative option starters
991 A string of alternative option starter characters may be passed as the
992 first argument (or the first argument after a leading hash reference
993 argument).
994
995 my $len = 0;
996 GetOptions ('/', 'length=i' => $len);
997
998 Now the command line may look like:
999
1000 /length 24 -- arg
1001
1002 Note that to terminate options processing still requires a double dash
1003 "--".
1004
1005 GetOptions() will not interpret a leading "<>" as option starters if
1006 the next argument is a reference. To force "<" and ">" as option
1007 starters, use "><". Confusing? Well, using a starter argument is
1008 strongly deprecated anyway.
1009
1010 Configuration variables
1011 Previous versions of Getopt::Long used variables for the purpose of
1012 configuring. Although manipulating these variables still work, it is
1013 strongly encouraged to use the "Configure" routine that was introduced
1014 in version 2.17. Besides, it is much easier.
1015
1017 Pushing multiple values in a hash option
1018 Sometimes you want to combine the best of hashes and arrays. For
1019 example, the command line:
1020
1021 --list add=first --list add=second --list add=third
1022
1023 where each successive 'list add' option will push the value of add into
1024 array ref $list->{'add'}. The result would be like
1025
1026 $list->{add} = [qw(first second third)];
1027
1028 This can be accomplished with a destination routine:
1029
1030 GetOptions('list=s%' =>
1031 sub { push(@{$list{$_[1]}}, $_[2]) });
1032
1034 GetOptions does not return a false result when an option is not supplied
1035 That's why they're called 'options'.
1036
1037 GetOptions does not split the command line correctly
1038 The command line is not split by GetOptions, but by the command line
1039 interpreter (CLI). On Unix, this is the shell. On Windows, it is
1040 COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
1041
1042 It is important to know that these CLIs may behave different when the
1043 command line contains special characters, in particular quotes or
1044 backslashes. For example, with Unix shells you can use single quotes
1045 ("'") and double quotes (""") to group words together. The following
1046 alternatives are equivalent on Unix:
1047
1048 "two words"
1049 'two words'
1050 two\ words
1051
1052 In case of doubt, insert the following statement in front of your Perl
1053 program:
1054
1055 print STDERR (join("|",@ARGV),"\n");
1056
1057 to verify how your CLI passes the arguments to the program.
1058
1059 Undefined subroutine &main::GetOptions called
1060 Are you running Windows, and did you write
1061
1062 use GetOpt::Long;
1063
1064 (note the capital 'O')?
1065
1066 How do I put a "-?" option into a Getopt::Long?
1067 You can only obtain this using an alias, and Getopt::Long of at least
1068 version 2.13.
1069
1070 use Getopt::Long;
1071 GetOptions ("help|?"); # -help and -? will both set $opt_help
1072
1073 Other characters that can't appear in Perl identifiers are also
1074 supported as aliases with Getopt::Long of at least version 2.39.
1075
1076 As of version 2.32 Getopt::Long provides auto-help, a quick and easy
1077 way to add the options --help and -? to your program, and handle them.
1078
1079 See "auto_help" in section "Configuring Getopt::Long".
1080
1082 Johan Vromans <jvromans@squirrel.nl>
1083
1085 This program is Copyright 1990,2015 by Johan Vromans. This program is
1086 free software; you can redistribute it and/or modify it under the terms
1087 of the Perl Artistic License or the GNU General Public License as
1088 published by the Free Software Foundation; either version 2 of the
1089 License, or (at your option) any later version.
1090
1091 This program is distributed in the hope that it will be useful, but
1092 WITHOUT ANY WARRANTY; without even the implied warranty of
1093 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1094 General Public License for more details.
1095
1096 If you do not have a copy of the GNU General Public License write to
1097 the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
1098 USA.
1099
1100
1101
1102perl v5.28.1 2017-05-27 Getopt::Long(3)