1NAME
2 Getopt::Lucid - Clear, readable syntax for command line processing
3
4VERSION
5 version 1.10
6
7SYNOPSIS
8 use Getopt::Lucid qw( :all );
9
10 # basic option specifications with aliases
11
12 @specs = (
13 Switch("version|V"),
14 Counter("verbose|v"),
15 Param("config|C"),
16 List("lib|l|I"),
17 Keypair("define"),
18 Switch("help|h")
19 );
20
21 $opt = Getopt::Lucid->getopt( \@specs )->validate;
22
23 $verbosity = $opt->get_verbose;
24 @libs = $opt->get_lib;
25 %defs = $opt->get_define;
26
27 %all_options = $opt->options;
28
29 # advanced option specifications
30
31 @adv_spec = (
32 Param("input"),
33 Param("mode")->default("tcp"), # defaults
34 Param("host")->needs("port"), # dependencies
35 Param("port")->valid(qr/\d+/), # regex validation
36 Param("config")->valid(sub { -r }),# custom validation
37 Param("help")->anycase, # case insensitivity
38 );
39 $opt = Getopt::Lucid->getopt( \@adv_spec );
40 $opt->validate({ 'requires' => ['input'] });
41
42 # example with a config file
43
44 $opt = Getopt::Lucid->getopt( \@adv_spec );
45 use Config::Std;
46 if ( -r $opt->get_config ) {
47 read_config( $opt->get_config() => my %config_hash );
48 $opt->merge_defaults( $config_hash{''} );
49 }
50
51DESCRIPTION
52 The goal of this module is providing good code readability and clarity
53 of intent for command-line option processing. While readability is a
54 subjective standard, Getopt::Lucid relies on a more verbose,
55 plain-English option specification as compared against the more symbolic
56 approach of Getopt::Long. Key features include:
57
58 * Five option types: switches, counters, parameters, lists, and key
59 pairs
60
61 * Three option styles: long, short (including bundled), and bare
62 (without dashes)
63
64 * Specification of defaults, required options and option dependencies
65
66 * Validation of options with regexes or subroutines
67
68 * Negation of options on the command line
69
70 * Support for parsing any array, not just the default @ARGV
71
72 * Incorporation of external defaults (e.g. from a config file) with
73 user control of precedence
74
75USAGE
76 Option Styles, Naming and "Strictness"
77 Getopt::Lucid support three kinds of option styles: long-style
78 ("--foo"), short-style ("-f") and bareword style ("foo"). Short-style
79 options are automatically unbundled during command line processing if a
80 single dash is followed by more than one letter (e.g. "-xzf" becomes "-x
81 -z -f" ).
82
83 Each option is identified in the specification with a string consisting
84 of the option "name" followed by zero or more "aliases", with any alias
85 (and each subsequent alias) separated by a vertical bar character. E.g.:
86
87 "lib|l|I" means name "lib", alias "l" and alias "I"
88
89 Names and aliases must begin with an alphanumeric character, but
90 subsequently may also include both underscore and dash. (E.g. both
91 "input-file" and "input_file" are valid.) While names and aliases are
92 interchangeable when provided on the command line, the "name" portion is
93 used with the accessors for each option (see "Accessors and Mutators").
94
95 Any of the names and aliases in the specification may be given in any of
96 the three styles. By default, Getopt::Lucid works in "magic" mode, in
97 which option names or aliases may be specified with or without leading
98 dashes, and will be parsed from the command line whether or not they
99 have corresponding dashes. Single-character names or aliases may be read
100 with no dash, one dash or two dashes. Multi-character names or aliases
101 must have either no dashes or two dashes. E.g.:
102
103 * Both "foo" and "--foo" as names in the specification may be read
104 from the command line as either "--foo" or "foo"
105
106 * The specification name "f" may be read from the command line as
107 "--f", "-f", or just "f"
108
109 In practice, this means that the specification need not use dashes, but
110 if used on the command line, they will be treated appropriately.
111
112 Alternatively, Getopt::Lucid can operate in "strict" mode by setting the
113 C<strict> parameter to a true value. In strict mode, option names and
114 aliases may still be specified in any of the three styles, but they will
115 only be parsed from the command line if they are used in exactly the
116 same style. E.g., given the name and alias "--help|-h", only "--help"
117 and "-h" are valid for use on the command line.
118
119 Option Specification Constructors
120 Options specifications are provided to Getopt::Lucid in an array.
121 Entries in the array must be created with one of several special
122 constructor functions that return a specification object. These
123 constructor functions may be imported either individually or as a group
124 using the import tag ":all" (e.g. "use Getopt::Lucid qw(:all);").
125
126 The form of the constructor is:
127
128 TYPE( NAME_ARGUMENT );
129
130 The constructor function name indicates the type of option. The name
131 argument is a string with the names and aliases separated by vertical
132 bar characters.
133
134 The five option specification constructors are:
135
136 Switch()
137 A true/false value. Defaults to false. The appearance of an option of
138 this type on the command line sets it to true.
139
140 Counter()
141 A numerical counter. Defaults to 0. The appearance of an option of this
142 type on the command line increments the counter by one.
143
144 Param()
145 A variable taking an argument. Defaults to "" (the empty string). When
146 an option of this type appears on the command line, the value of the
147 option is set in one of two ways -- appended with an equals sign or from
148 the next argument on the command line:
149
150 --name=value
151 --name value
152
153 In the case where white space is used to separate the option name and
154 the value, if the value looks like an option, an exception will be
155 thrown:
156
157 --name --value # throws an exception
158
159 List()
160 This is like "Param()" but arguments are pushed onto a list. The default
161 list is empty.
162
163 Keypair()
164 A variable taking an argument pair, which are added to a hash. Arguments
165 are handled as with "Param()", but the argument itself must have a key
166 and value joined by an equals sign.
167
168 --name=key=value
169 --name key=value
170
171 Option modifiers
172 An option specification can be further modified with the following
173 methods, each of which return the object modified so that modifier
174 chaining is possible. E.g.:
175
176 @spec = (
177 Param("input")->default("/dev/random")->needs("output"),
178 Param("output")->default("/dev/null"),
179 );
180
181 valid()
182 Sets the validation parameter(s) for an option.
183
184 @spec = (
185 Param("port")->valid(qr/\d+/), # regex validation
186 Param("config")->valid(sub { -r }), # custom validation
187 Keypair("define")
188 ->valid(\&_valid_key, \&valid_value), # keypairs take two
189 );
190
191 See the "Validation" section, below, for more.
192
193 default()
194 Changes the default for the option to the argument(s) of "default()".
195 List and hashes can take either a list or a reference to an array or
196 hash, respectively.
197
198 @spec = (
199 Switch("debug")->default(1),
200 Counter("verbose")->default(3),
201 Param("config")->default("/etc/profile"),
202 List("dirs")->default(qw( /var /home )),
203 Keypair("define")->default( arch => "i386" ),
204 );
205
206 needs()
207 Takes as an argument a list of option names or aliases of dependencies.
208 If the option this modifies appears on the command line, each of the
209 options given as an argument must appear on the command line as well or
210 an exception is thrown.
211
212 @spec = (
213 Param("input")->needs("output"),
214 Param("output"),
215 );
216
217 anycase()
218 Indicates that the associated option names/aliases may appear on the
219 command line in lowercase, uppercase, or any mixture of the two. No
220 argument is needed.
221
222 @spec = (
223 Switch("help|h")->anycase(), # "Help", "HELP", etc.
224 );
225
226 doc()
227 Sets the documentation string for an option.
228
229 @spec = (
230 Param("output")->doc("write output to the specified file"),
231 );
232
233 This string shows up in the "usage" method.
234
235 Validation
236 Validation happens in two stages. First, individual parameters may have
237 validation criteria added to them. Second, the parsed options object may
238 be validated by checking that all requirements collectively are met.
239
240 Parameter validation
241 The Param, List, and Keypair option types may be provided an optional
242 validation specification. Values provided on the command line will be
243 validated according to the specification or an exception will be thrown.
244
245 A validation specification can be either a regular expression, or a
246 reference to a subroutine. Keypairs take up to two validation
247 specifiers. The first is applied to keys and the second is applied to
248 values; either can be left undef to ignore validation. (More complex
249 validation of specific values for specific keys must be done manually.)
250
251 Validation is also applied to default values provided via the
252 "default()" modifier or later modified with "append_defaults",
253 "merge_defaults", or "replace_defaults". This ensures internal
254 consistency.
255
256 If no default is explicitly provided, validation is only applied if the
257 option appears on the command line. (In other words, the built-in
258 defaults are always considered valid if the option does not appear.) If
259 this is not desired, the "required" option to the "validate" method
260 should be used to force users to provide an explicit value.
261
262 # Must be provided and is thus always validated
263 @spec = ( Param("width")->valid(qr/\d+/) );
264 $opt = Getopt::Lucid->getopt(\@spec);
265 $opt->validate( {requires => ['width']} );
266
267 For validation subroutines, the value found on the command line is
268 passed as the first element of @_, and $_ is also set equal to the first
269 element. (N.B. Changing $_ will not change the value that is captured.)
270 The value validates if the subroutine returns a true value.
271
272 For validation with regular expressions, consider using Regexp::Common
273 for a ready library of validation options.
274
275 Older versions of Getopt::Lucid used validation arguments provided in
276 the Spec constructor. This is still supported, but is deprecated and
277 discouraged. It may be removed in a future version of Getopt::Lucid.
278
279 # deprecated
280 Param("height", qr/\d+/)
281
282 Options object validation
283 The "validate" method should be called on the result of "getopt". This
284 will check that all parameter prerequisites defined by "needs" have been
285 met. It also takes a hashref of arguments. The optional "requires"
286 argument gives an arrayref of parameters that must exist.
287
288 The reason that object validation is done separate from "getopt" is to
289 allow for better control over different options that might be required
290 or to allow some dependencies (i.e. from "needs") to be met via a
291 configuration file.
292
293 @spec = (
294 Param("action")->needs(qw/user password/),
295 Param("user"),
296 Param("password"),
297 );
298 $opt = Getopt::Lucid->getopt(\@spec);
299 $opt->merge_defaults( read_config() ); # provides 'user' & 'password'
300 $opt->validate({requires => ['action']});
301
302 Parsing the Command Line
303 Technically, Getopt::Lucid scans an array for command line options, not
304 a command-line string. By default, this array is @ARGV (though other
305 arrays can be used -- see "new()"), which is typically provided by the
306 operating system according to system-specific rules.
307
308 When Getopt::Lucid processes the array, it scans the array in order,
309 removing any specified command line options and any associated
310 arguments, and leaving behind any unrecognized elements in the array. If
311 an element consisting solely of two-dashes ("--") is found, array
312 scanning is terminated at that point. Any options found during scanning
313 are applied in order. E.g.:
314
315 @ARGV = qw( --lib /tmp --lib /var );
316 my $opt = Getopt::Lucid->getopt( [ List("lib") ] );
317 print join ", " $opt->lib;
318 # prints "/tmp, /var"
319
320 If an element encountered in processing begins with a dash, but is not
321 recognized as a short-form or long-form option name or alias, an
322 exception will be thrown.
323
324 Negation
325 Getopt::Lucid also supports negating options. Options are negated if the
326 option is specified with "no-" or "--no-" prefixed to a name or alias.
327 By default, negation clears the option: Switch and Counter options are
328 set to zero; Param options are set to ""; List and Keypair options are
329 set to an empty list and empty hash, respectively. For List and Keypair
330 options, it is also possible to negate a specific list element or hash
331 key by placing an equals sign and the list element or key immediately
332 after the option name:
333
334 --no-lib=/tmp --no-define=arch
335 # removes "/tmp" from lib and the "arch" key from define
336
337 As with all options, negation is processed in order, allowing a "reset"
338 in the middle of command line processing. This may be useful for those
339 using command aliases who wish to "switch off" options in the alias.
340 E.g, in Unix:
341
342 $ alias wibble = wibble.pl --verbose
343 $ wibble --no-verbose
344
345 # @ARGV would contain ( "--verbose", "--no-verbose" )
346
347 This also may have applications in post-processing configuration files
348 (see "Managing Defaults and Config Files").
349
350 Accessors and Mutators
351 After processing the command-line array, the values of the options may
352 be read or modified using accessors/mutators of the form "get_NAME" and
353 "set_NAME", where NAME represents the option name in the specification
354 without any leading dashes. E.g.
355
356 @spec = (
357 Switch("--test|-t"),
358 List("--lib|-L"),
359 Keypair("--define|-D"),
360 );
361
362 $opt = Getopt::Lucid->getopt( \@spec );
363 print $opt->get_test ? "True" : "False";
364 $opt->set_test(1);
365
366 For option names with dashes, underscores should be substituted in the
367 accessor calls. E.g.
368
369 @spec = (
370 Param("--input-file|-i")
371 );
372
373 $opt = Getopt::Lucid->getopt( \@spec );
374 print $opt->get_input_file;
375
376 This can create an ambiguous case if a similar option exists with
377 underscores in place of dashes. (E.g. "input_file" and "input-file".)
378 Users can safely avoid these problems by choosing to use either dashes
379 or underscores exclusively and not mixing the two styles.
380
381 List and Keypair options are returned as flattened lists:
382
383 my @lib = $opt->get_lib;
384 my %define = $opt->get_define;
385
386 Using the "set_NAME" mutator is not recommended and should be used with
387 caution. No validation is performed and changes will be lost if the
388 results of processing the command line array are recomputed (e.g, such
389 as occurs if new defaults are applied). List and Keypair options
390 mutators take a list, not references.
391
392 Managing Defaults and Config Files
393 A typical problem for command-line option processing is the precedence
394 relationship between default option values specified within the program,
395 default option values stored in a configuration file or in environment
396 variables, and option values specified on the command-line, particularly
397 when the command-line specifies an alternate configuration file.
398
399 Getopt::Lucid takes the following approach to this problem:
400
401 * Initial default values may be specified as part of the option
402 specification (using the "default()" modifier)
403
404 * Default values from the option specification may be modified or
405 replaced entirely with default values provided in an external hash
406 (such as from a standard config file or environment variables)
407
408 * When the command-line array is processed, options and their
409 arguments are stored in the order they appeared in the command-line
410 array
411
412 * The stored options are applied in-order to modify or replace the set
413 of "current" default option values
414
415 * If default values are subsequently changed (such as from an
416 alternative configuration file), the stored options are re-applied
417 in-order to the new set of default option values
418
419 With this approach, the resulting option set is always the result of
420 applying options (or negations) from the command-line array to a set of
421 default-values. Users have complete freedom to apply whatever precedence
422 rules they wish to the default values and may even change default values
423 after the command-line array is processed without losing the options
424 given on the command line.
425
426 Getopt::Lucid provides several functions to assist in manipulating
427 default values:
428
429 * "merge_defaults()" -- new defaults overwrite any matching, existing
430 defaults. KeyPairs hashes and List arrays are replaced entirely with
431 new defaults
432
433 * "append_defaults()" -- new defaults overwrite any matching, existing
434 defaults, except for Counter and List options, which have the new
435 defaults added and appended, respectively, and KeyPair options,
436 which are flattened into any existing default hash
437
438 * "replace_defaults()" -- new defaults replace existing defaults; any
439 options not provided in the new defaults are reset to zero/empty,
440 ignoring any default given in the option specification
441
442 * "reset_defaults()" -- returns defaults to values given in the
443 options specification
444
445 Exceptions and Error Handling
446 Getopt::Lucid uses Exception::Class for exceptions. When a major error
447 occurs, Getopt::Lucid will die and throw one of three Exception::Class
448 subclasses:
449
450 * "Getopt::Lucid::Exception::Usage" -- thrown when Getopt::Lucid
451 methods are called incorrectly
452
453 * "Getopt::Lucid::Exception::Spec" -- thrown when the specification
454 array contains incorrect or invalid data
455
456 * "Getopt::Lucid::Exception::ARGV" -- thrown when the command-line is
457 processed and fails to pass specified validation, requirements, or
458 is otherwise determined to be invalid
459
460 These exceptions may be caught using an "eval" block and allow the
461 calling program to respond differently to each class of exception.
462
463 Ambiguous Cases and Gotchas
464 One-character aliases and "anycase"
465 @spec = (
466 Counter("verbose|v")->anycase,
467 Switch("version|V")->anycase,
468 );
469
470 Consider the spec above. By specifying "anycase" on these, "verbose",
471 "Verbose", "VERBOSE" are all acceptable, as are "version", "Version" and
472 so on. (Including long-form versions of these, too, if "magic" mode is
473 used.) However, what if the command line has "-v" or even "-v -V"? In
474 this case, the rule is that exact case matches are used before
475 case-insensitive matches are searched. Thus, "-v" can only match
476 "verbose", despite the "anycase" modification, and likewise "-V" can
477 only match "version".
478
479 Identical names except for dashes and underscores
480 @spec = (
481 Param("input-file"),
482 Switch("input_file"),
483 );
484
485 Consider the spec above. These are two, separate, valid options, but a
486 call to the accessor "get_input_file" is ambiguous and may return either
487 option, depending on which first satisfies a "fuzzy-matching" algorithm
488 inside the accessor code. Avoid identical names with mixed dash and
489 underscore styles.
490
491METHODS
492 new()
493 $opt = Getopt::Lucid->new( \@option_spec );
494 $opt = Getopt::Lucid->new( \@option_spec, \%parameters );
495 $opt = Getopt::Lucid->new( \@option_spec, \@option_array );
496 $opt = Getopt::Lucid->new( \@option_spec, \@option_array, \%parameters );
497
498 Creates a new Getopt::Lucid object. An array reference to an option spec
499 is required as an argument. (See "USAGE" for a description of the object
500 spec). By default, objects will be set to read @ARGV for command line
501 options. An optional second argument with a reference to an array will
502 use that array for option processing instead. The final argument may be
503 a hashref of parameters. The only valid parameter currently is:
504
505 * strict -- enables strict mode when true
506
507 For typical cases, users will likely prefer to call "getopt" instead,
508 which creates a new object and parses the command line with a single
509 function call.
510
511 validate()
512 $opt->validate();
513 $opt->validate( \%arguments );
514
515 Takes an optional argument hashref, validates that all requirements and
516 prerequisites are met or throws an error. Valid argument keys are:
517
518 * "requires" -- an arrayref of options that must exist in the options
519 object.
520
521 This method returns the object for convenient chaining:
522
523 $opt = Getopt::Lucid->getopt(\@spec)->validate;
524
525 append_defaults()
526 %options = append_defaults( %config_hash );
527 %options = append_defaults( \%config_hash );
528
529 Takes a hash or hash reference of new default values, modifies the
530 stored defaults, recalculates the result of processing the command line
531 with the revised defaults, and returns a hash with the resulting
532 options. Each key/value pair in the passed hash is added to the stored
533 defaults. For Switch and Param options, the value in the passed hash
534 will overwrite any preexisting value. For Counter options, the value is
535 added to any preexisting value. For List options, the value (or values,
536 if the value is an array reference) will be pushed onto the end of the
537 list of existing values. For Keypair options, the key/value pairs will
538 be added to the existing hash, overwriting existing key/value pairs
539 (just like merging two hashes). Keys which are not valid names from the
540 options specification will be ignored.
541
542 defaults()
543 %defaults = $opt->defaults();
544
545 Returns a hash containing current default values. Keys are names from
546 the option specification (without any leading dashes). These defaults
547 represent the baseline values that are modified by the parsed command
548 line options.
549
550 getopt()
551 $opt = Getopt::Lucid->getopt( \@option_spec );
552 $opt = Getopt::Lucid->getopt( \@option_spec, \@option_array );
553 $opt->getopt();
554
555 Parses the command line array (@ARGV by default). When called as a class
556 function, "getopt" takes the same arguments as "new", calls "new" to
557 create an object before parsing the command line, and returns the new
558 object. When called as an object method, it takes no arguments and
559 returns itself.
560
561 For convenience, C<getopts()> is a alias for C<getopt()>.
562
563 merge_defaults()
564 %options = merge_defaults( %config_hash );
565 %options = merge_defaults( \%config_hash );
566
567 Takes a hash or hash reference of new default values, modifies the
568 stored defaults, recalculates the result of processing the command line
569 with the revised defaults, and returns a hash with the resulting
570 options. Each key/value pair in the passed hash is added to the stored
571 defaults, overwriting any preexisting value. Keys which are not valid
572 names from the options specification will be ignored.
573
574 names()
575 @names = $opt->names();
576
577 Returns the list of names in the options specification. Each name
578 represents a key in the hash of options provided by "options".
579
580 options()
581 %options = $opt->options();
582
583 Returns a deep copy of the options hash. Before "getopt" is called, its
584 behavior is undefined. After "getopt" is called, this will return the
585 result of modifying the defaults with the results of command line
586 processing.
587
588 replace_defaults()
589 %options = replace_defaults( %config_hash );
590 %options = replace_defaults( \%config_hash );
591
592 Takes a hash or hash reference of new default values, replaces the
593 stored defaults, recalculates the result of processing the command line
594 with the revised defaults, and returns a hash with the resulting
595 options. Each key/value pair in the passed hash replaces existing
596 defaults, including those given in the option specifications. Keys which
597 are not valid names from the option specification will be ignored.
598
599 reset_defaults()
600 %options = reset_defaults();
601
602 Resets the stored defaults to the original values from the options
603 specification, recalculates the result of processing the command line
604 with the restored defaults, and returns a hash with the resulting
605 options. This undoes the effect of a "merge_defaults" or "add_defaults"
606 call.
607
608 usage()
609 Returns a string of usage information derived from the options spec,
610 including any "doc" modifiers. Because invalid options throw exceptions,
611 if you want to provide usage, you should separately invoke "new" and
612 "getopt"
613
614 my $opt = Getopt::Lucid->new( \@spec );
615 eval { $opt->getopt() };
616 if ($@) {
617 print "$@\n" && print $opt->usage and exit 1
618 if ref $@ eq 'Getopt::Lucid::Exception::ARGV';
619 ref $@ ? $@->rethrow : die $@;
620 }
621
622API CHANGES
623 In 1.00, the following API changes have been made:
624
625 * "new()" now takes an optional hashref of parameters as the last
626 argument
627
628 * The global $STRICT variable has been replaced with a per-object
629 parameter "strict"
630
631 * The "required" modifier has been removed and a new "validate" method
632 has been added to facilitate late/custom checks of required options
633
634SEE ALSO
635 * Config::Tiny
636
637 * Config::Simple
638
639 * Config::Std
640
641 * Getopt::Long
642
643 * Regexp::Common
644
645BUGS
646 Please report any bugs or feature using the CPAN Request Tracker. Bugs
647 can be submitted through the web interface at
648 <http://rt.cpan.org/Dist/Display.html?Queue=Getopt-Lucid>
649
650 When submitting a bug or request, please include a test-file or a patch
651 to an existing test-file that illustrates the bug or desired feature.
652
653SUPPORT
654 Bugs / Feature Requests
655 Please report any bugs or feature requests through the issue tracker at
656 <https://github.com/dagolden/Getopt-Lucid/issues>. You will be notified
657 automatically of any progress on your issue.
658
659 Source Code
660 This is open source software. The code repository is available for
661 public review and contribution under the terms of the license.
662
663 <https://github.com/dagolden/Getopt-Lucid>
664
665 git clone https://github.com/dagolden/Getopt-Lucid.git
666
667AUTHOR
668 David Golden <dagolden@cpan.org>
669
670CONTRIBUTORS
671 * Chris White <cxwembedded@gmail.com>
672
673 * David Golden <xdg@xdg.me>
674
675 * David Precious <davidp@preshweb.co.uk>
676
677 * James E Keenan <jkeenan@cpan.org>
678
679 * Kevin McGrath <kmcgrath@cpan.org>
680
681 * Nova Patch <patch@cpan.org>
682
683 * Robert Bohne <rbo@cpan.org>
684
685 * thilp <thilp@thilp.net>
686
687COPYRIGHT AND LICENSE
688 This software is Copyright (c) 2019 by David Golden.
689
690 This is free software, licensed under:
691
692 The Apache License, Version 2.0, January 2004
693
694