1Getopt::Lucid(3)      User Contributed Perl Documentation     Getopt::Lucid(3)
2
3
4

NAME

6       Getopt::Lucid - Clear, readable syntax for command line processing
7

VERSION

9       version 1.09
10

SYNOPSIS

12          use Getopt::Lucid qw( :all );
13
14          # basic option specifications with aliases
15
16          @specs = (
17            Switch("version|V"),
18            Counter("verbose|v"),
19            Param("config|C"),
20            List("lib|l|I"),
21            Keypair("define"),
22            Switch("help|h")
23          );
24
25          $opt = Getopt::Lucid->getopt( \@specs )->validate;
26
27          $verbosity = $opt->get_verbose;
28          @libs = $opt->get_lib;
29          %defs = $opt->get_define;
30
31          %all_options = $opt->options;
32
33          # advanced option specifications
34
35          @adv_spec = (
36            Param("input"),
37            Param("mode")->default("tcp"),     # defaults
38            Param("host")->needs("port"),      # dependencies
39            Param("port")->valid(qr/\d+/),     # regex validation
40            Param("config")->valid(sub { -r }),# custom validation
41            Param("help")->anycase,            # case insensitivity
42          );
43          $opt = Getopt::Lucid->getopt( \@adv_spec );
44          $opt->validate({ 'requires' => ['input'] });
45
46          # example with a config file
47
48          $opt = Getopt::Lucid->getopt( \@adv_spec );
49          use Config::Std;
50          if ( -r $opt->get_config ) {
51            read_config( $opt->get_config() => my %config_hash );
52            $opt->merge_defaults( $config_hash{''} );
53          }
54

DESCRIPTION

56       The goal of this module is providing good code readability and clarity
57       of intent for command-line option processing.  While readability is a
58       subjective standard, Getopt::Lucid relies on a more verbose, plain-
59       English option specification as compared against the more symbolic
60       approach of Getopt::Long.  Key features include:
61
62       ·   Five option types: switches, counters, parameters, lists, and key
63           pairs
64
65       ·   Three option styles: long, short (including bundled), and bare
66           (without dashes)
67
68       ·   Specification of defaults, required options and option dependencies
69
70       ·   Validation of options with regexes or subroutines
71
72       ·   Negation of options on the command line
73
74       ·   Support for parsing any array, not just the default @ARGV
75
76       ·   Incorporation of external defaults (e.g. from a config file) with
77           user control of precedence
78

USAGE

80   Option Styles, Naming and "Strictness"
81       Getopt::Lucid support three kinds of option styles: long-style
82       ("--foo"), short-style ("-f") and bareword style ("foo").  Short-style
83       options are automatically unbundled during command line processing if a
84       single dash is followed by more than one letter (e.g. "-xzf" becomes
85       "-x -z -f" ).
86
87       Each option is identified in the specification with a string consisting
88       of the option "name" followed by zero or more "aliases", with any alias
89       (and each subsequent alias) separated by a vertical bar character.
90       E.g.:
91
92          "lib|l|I" means name "lib", alias "l" and alias "I"
93
94       Names and aliases must begin with an alphanumeric character, but
95       subsequently may also include both underscore and dash.  (E.g. both
96       "input-file" and "input_file" are valid.)  While names and aliases are
97       interchangeable when provided on the command line, the "name" portion
98       is used with the accessors for each option (see "Accessors and
99       Mutators").
100
101       Any of the names and aliases in the specification may be given in any
102       of the three styles.  By default, Getopt::Lucid works in "magic" mode,
103       in which option names or aliases may be specified with or without
104       leading dashes, and will be parsed from the command line whether or not
105       they have corresponding dashes.  Single-character names or aliases may
106       be read with no dash, one dash or two dashes.  Multi-character names or
107       aliases must have either no dashes or two dashes.  E.g.:
108
109       ·   Both "foo" and "--foo" as names in the specification may be read
110           from the command line as either "--foo" or "foo"
111
112       ·   The specification name "f" may be read from the command line as
113           "--f", "-f", or just "f"
114
115       In practice, this means that the specification need not use dashes, but
116       if used on the command line, they will be treated appropriately.
117
118       Alternatively, Getopt::Lucid can operate in "strict" mode by setting
119       the C<strict> parameter to a true value.  In strict mode, option names
120       and aliases may still be specified in any of the three styles, but they
121       will only be parsed from the command line if they are used in exactly
122       the same style.  E.g., given the name and alias "--help|-h", only
123       "--help" and "-h" are valid for use on the command line.
124
125   Option Specification Constructors
126       Options specifications are provided to Getopt::Lucid in an array.
127       Entries in the array must be created with one of several special
128       constructor functions that return a specification object.  These
129       constructor functions may be imported either individually or as a group
130       using the import tag ":all" (e.g.  "use Getopt::Lucid qw(:all);").
131
132       The form of the constructor is:
133
134         TYPE( NAME_ARGUMENT );
135
136       The constructor function name indicates the type of option.  The name
137       argument is a string with the names and aliases separated by vertical
138       bar characters.
139
140       The five option specification constructors are:
141
142       Switch()
143
144       A true/false value.  Defaults to false.  The appearance of an option of
145       this type on the command line sets it to true.
146
147       Counter()
148
149       A numerical counter.  Defaults to 0.  The appearance of an option of
150       this type on the command line increments the counter by one.
151
152       Param()
153
154       A variable taking an argument.  Defaults to "" (the empty string).
155       When an option of this type appears on the command line, the value of
156       the option is set in one of two ways -- appended with an equals sign or
157       from the next argument on the command line:
158
159          --name=value
160          --name value
161
162       In the case where white space is used to separate the option name and
163       the value, if the value looks like an option, an exception will be
164       thrown:
165
166          --name --value        # throws an exception
167
168       List()
169
170       This is like "Param()" but arguments are pushed onto a list.  The
171       default list is empty.
172
173       Keypair()
174
175       A variable taking an argument pair, which are added to a hash.
176       Arguments are handled as with "Param()", but the argument itself must
177       have a key and value joined by an equals sign.
178
179          --name=key=value
180          --name key=value
181
182   Option modifiers
183       An option specification can be further modified with the following
184       methods, each of which return the object modified so that modifier
185       chaining is possible.  E.g.:
186
187          @spec = (
188            Param("input")->default("/dev/random")->needs("output"),
189            Param("output)->default("/dev/null"),
190          );
191
192       valid()
193
194       Sets the validation parameter(s) for an option.
195
196          @spec = (
197            Param("port")->valid(qr/\d+/),          # regex validation
198            Param("config")->valid(sub { -r }),     # custom validation
199            Keypair("define")
200              ->valid(\&_valid_key, \&valid_value), # keypairs take two
201          );
202
203       See the "Validation" section, below, for more.
204
205       default()
206
207       Changes the default for the option to the argument(s) of "default()".
208       List and hashes can take either a list or a reference to an array or
209       hash, respectively.
210
211          @spec = (
212            Switch("debug")->default(1),
213            Counter("verbose")->default(3),
214            Param("config")->default("/etc/profile"),
215            List("dirs")->default(qw( /var /home )),
216            Keypair("define")->default( arch => "i386" ),
217          );
218
219       needs()
220
221       Takes as an argument a list of option names or aliases of dependencies.
222       If the option this modifies appears on the command line, each of the
223       options given as an argument must appear on the command line as well or
224       an exception is thrown.
225
226          @spec = (
227            Param("input")->needs("output"),
228            Param("output),
229          );
230
231       anycase()
232
233       Indicates that the associated option names/aliases may appear on the
234       command line in lowercase, uppercase, or any mixture of the two.  No
235       argument is needed.
236
237          @spec = (
238            Switch("help|h")->anycase(),    # "Help", "HELP", etc.
239          );
240
241       doc()
242
243       Sets the documentation string for an option.
244
245            @spec = (
246              Param("output")->doc("write output to the specified file"),
247            );
248
249       This string shows up in the "usage" method.
250
251   Validation
252       Validation happens in two stages.  First, individual parameters may
253       have validation criteria added to them.  Second, the parsed options
254       object may be validated by checking that all requirements collectively
255       are met.
256
257       Parameter validation
258
259       The Param, List, and Keypair option types may be provided an optional
260       validation specification.  Values provided on the command line will be
261       validated according to the specification or an exception will be
262       thrown.
263
264       A validation specification can be either a regular expression, or a
265       reference to a subroutine.  Keypairs take up to two validation
266       specifiers.  The first is applied to keys and the second is applied to
267       values; either can be left undef to ignore validation.  (More complex
268       validation of specific values for specific keys must be done manually.)
269
270       Validation is also applied to default values provided via the
271       "default()" modifier or later modified with "append_defaults",
272       "merge_defaults", or "replace_defaults".  This ensures internal
273       consistency.
274
275       If no default is explicitly provided, validation is only applied if the
276       option appears on the command line. (In other words, the built-in
277       defaults are always considered valid if the option does not appear.)
278       If this is not desired, the "required" option to the "validate" method
279       should be used to force users to provide an explicit value.
280
281          # Must be provided and is thus always validated
282          @spec = ( Param("width")->valid(qr/\d+/) );
283          $opt = Getopt::Lucid->getopt(\@spec);
284          $opt->validate( {requires => ['width']} );
285
286       For validation subroutines, the value found on the command line is
287       passed as the first element of @_, and $_ is also set equal to the
288       first element.  (N.B. Changing $_ will not change the value that is
289       captured.)  The value validates if the subroutine returns a true value.
290
291       For validation with regular expressions, consider using Regexp::Common
292       for a ready library of validation options.
293
294       Older versions of Getopt::Lucid used validation arguments provided in
295       the Spec constructor.  This is still supported, but is deprecated and
296       discouraged. It may be removed in a future version of Getopt::Lucid.
297
298          # deprecated
299          Param("height", qr/\d+/)
300
301       Options object validation
302
303       The "validate" method should be called on the result of "getopt".  This
304       will check that all parameter prerequisites defined by "needs" have
305       been met.  It also takes a hashref of arguments.  The optional
306       "requires" argument gives an arrayref of parameters that must exist.
307
308       The reason that object validation is done separate from "getopt" is to
309       allow for better control over different options that might be required
310       or to allow some dependencies (i.e. from "needs") to be met via a
311       configuration file.
312
313          @spec = (
314            Param("action")->needs(qw/user password/),
315            Param("user"),
316            Param("password"),
317          );
318          $opt = Getopt::Lucid->getopt(\@spec);
319          $opt->merge_defaults( read_config() ); # provides 'user' & 'password'
320          $opt->validate({requires => ['action']});
321
322   Parsing the Command Line
323       Technically, Getopt::Lucid scans an array for command line options, not
324       a command-line string.  By default, this array is @ARGV (though other
325       arrays can be used -- see "new()"), which is typically provided by the
326       operating system according to system-specific rules.
327
328       When Getopt::Lucid processes the array, it scans the array in order,
329       removing any specified command line options and any associated
330       arguments, and leaving behind any unrecognized elements in the array.
331       If an element consisting solely of two-dashes ("--") is found, array
332       scanning is terminated at that point.  Any options found during
333       scanning are applied in order.  E.g.:
334
335          @ARGV = qw( --lib /tmp --lib /var );
336          my $opt = Getopt::Lucid->getopt( [ List("lib") ] );
337          print join ", " $opt->lib;
338          # prints "/tmp, /var"
339
340       If an element encountered in processing begins with a dash, but is not
341       recognized as a short-form or long-form option name or alias, an
342       exception will be thrown.
343
344   Negation
345       Getopt::Lucid also supports negating options.  Options are negated if
346       the option is specified with "no-" or "--no-" prefixed to a name or
347       alias.  By default, negation clears the option:  Switch and Counter
348       options are set to zero; Param options are set to ""; List and Keypair
349       options are set to an empty list and empty hash, respectively. For List
350       and Keypair options, it is also possible to negate a specific list
351       element or hash key by placing an equals sign and the list element or
352       key immediately after the option name:
353
354          --no-lib=/tmp --no-define=arch
355          # removes "/tmp" from lib and the "arch" key from define
356
357       As with all options, negation is processed in order, allowing a "reset"
358       in the middle of command line processing.  This may be useful for those
359       using command aliases who wish to "switch off" options in the alias.
360       E.g, in Unix:
361
362          $ alias wibble = wibble.pl --verbose
363          $ wibble --no-verbose
364
365          # @ARGV would contain ( "--verbose", "--no-verbose" )
366
367       This also may have applications in post-processing configuration files
368       (see "Managing Defaults and Config Files").
369
370   Accessors and Mutators
371       After processing the command-line array, the values of the options may
372       be read or modified using accessors/mutators of the form "get_NAME" and
373       "set_NAME", where NAME represents the option name in the specification
374       without any leading dashes. E.g.
375
376          @spec = (
377            Switch("--test|-t"),
378            List("--lib|-L"),
379            Keypair("--define|-D"),
380          );
381
382          $opt = Getopt::Lucid->getopt( \@spec );
383          print $opt->get_test ? "True" : "False";
384          $opt->set_test(1);
385
386       For option names with dashes, underscores should be substituted in the
387       accessor calls.  E.g.
388
389          @spec = (
390            Param("--input-file|-i")
391          );
392
393          $opt = Getopt::Lucid->getopt( \@spec );
394          print $opt->get_input_file;
395
396       This can create an ambiguous case if a similar option exists with
397       underscores in place of dashes.  (E.g. "input_file" and "input-file".)
398       Users can safely avoid these problems by choosing to use either dashes
399       or underscores exclusively and not mixing the two styles.
400
401       List and Keypair options are returned as flattened lists:
402
403          my @lib = $opt->get_lib;
404          my %define = $opt->get_define;
405
406       Using the "set_NAME" mutator is not recommended and should be used with
407       caution.  No validation is performed and changes will be lost if the
408       results of processing the command line array are recomputed (e.g, such
409       as occurs if new defaults are applied).  List and Keypair options
410       mutators take a list, not references.
411
412   Managing Defaults and Config Files
413       A typical problem for command-line option processing is the precedence
414       relationship between default option values specified within the
415       program, default option values stored in a configuration file or in
416       environment variables, and option values specified on the command-line,
417       particularly when the command-line specifies an alternate configuration
418       file.
419
420       Getopt::Lucid takes the following approach to this problem:
421
422       ·   Initial default values may be specified as part of the option
423           specification (using the "default()" modifier)
424
425       ·   Default values from the option specification may be modified or
426           replaced entirely with default values provided in an external hash
427           (such as from a standard config file or environment variables)
428
429       ·   When the command-line array is processed, options and their
430           arguments are stored in the order they appeared in the command-line
431           array
432
433       ·   The stored options are applied in-order to modify or replace the
434           set of "current" default option values
435
436       ·   If default values are subsequently changed (such as from an
437           alternative configuration file), the stored options are re-applied
438           in-order to the new set of default option values
439
440       With this approach, the resulting option set is always the result of
441       applying options (or negations) from the command-line array to a set of
442       default-values.  Users have complete freedom to apply whatever
443       precedence rules they wish to the default values and may even change
444       default values after the command-line array is processed without losing
445       the options given on the command line.
446
447       Getopt::Lucid provides several functions to assist in manipulating
448       default values:
449
450       ·   "merge_defaults()" -- new defaults overwrite any matching, existing
451           defaults.  KeyPairs hashes and List arrays are replaced entirely
452           with new defaults
453
454       ·   "append_defaults()" -- new defaults overwrite any matching,
455           existing defaults, except for Counter and List options, which have
456           the new defaults added and appended, respectively, and KeyPair
457           options, which are flattened into any existing default hash
458
459       ·   "replace_defaults()" -- new defaults replace existing defaults; any
460           options not provided in the new defaults are reset to zero/empty,
461           ignoring any default given in the option specification
462
463       ·   "reset_defaults()" -- returns defaults to values given in the
464           options specification
465
466   Exceptions and Error Handling
467       Getopt::Lucid uses Exception::Class for exceptions.  When a major error
468       occurs, Getopt::Lucid will die and throw one of three Exception::Class
469       subclasses:
470
471       ·   "Getopt::Lucid::Exception::Usage" -- thrown when Getopt::Lucid
472           methods are called incorrectly
473
474       ·   "Getopt::Lucid::Exception::Spec" -- thrown when the specification
475           array contains incorrect or invalid data
476
477       ·   "Getopt::Lucid::Exception::ARGV" -- thrown when the command-line is
478           processed and fails to pass specified validation, requirements, or
479           is otherwise determined to be invalid
480
481       These exceptions may be caught using an "eval" block and allow the
482       calling program to respond differently to each class of exception.
483
484   Ambiguous Cases and Gotchas
485       One-character aliases and "anycase"
486
487          @spec = (
488            Counter("verbose|v")->anycase,
489            Switch("version|V")->anycase,
490          );
491
492       Consider the spec above.  By specifying "anycase" on these, "verbose",
493       "Verbose", "VERBOSE" are all acceptable, as are "version", "Version"
494       and so on.  (Including long-form versions of these, too, if "magic"
495       mode is used.)  However, what if the command line has "-v" or even "-v
496       -V"?  In this case, the rule is that exact case matches are used before
497       case-insensitive matches are searched.  Thus, "-v" can only match
498       "verbose", despite the "anycase" modification, and likewise "-V" can
499       only match "version".
500
501       Identical names except for dashes and underscores
502
503          @spec = (
504            Param("input-file"),
505            Switch("input_file"),
506          );
507
508       Consider the spec above.  These are two, separate, valid options, but a
509       call to the accessor "get_input_file" is ambiguous and may return
510       either option, depending on which first satisfies a "fuzzy-matching"
511       algorithm inside the accessor code.  Avoid identical names with mixed
512       dash and underscore styles.
513

METHODS

515   new()
516         $opt = Getopt::Lucid->new( \@option_spec );
517         $opt = Getopt::Lucid->new( \@option_spec, \%parameters );
518         $opt = Getopt::Lucid->new( \@option_spec, \@option_array );
519         $opt = Getopt::Lucid->new( \@option_spec, \@option_array, \%parameters );
520
521       Creates a new Getopt::Lucid object.  An array reference to an option
522       spec is required as an argument.  (See "USAGE" for a description of the
523       object spec).  By default, objects will be set to read @ARGV for
524       command line options. An optional second argument with a reference to
525       an array will use that array for option processing instead.  The final
526       argument may be a hashref of parameters.  The only valid parameter
527       currently is:
528
529       ·   strict -- enables strict mode when true
530
531       For typical cases, users will likely prefer to call "getopt" instead,
532       which creates a new object and parses the command line with a single
533       function call.
534
535   validate()
536          $opt->validate();
537          $opt->validate( \%arguments );
538
539       Takes an optional argument hashref, validates that all requirements and
540       prerequisites are met or throws an error.  Valid argument keys are:
541
542       ·   "requires" -- an arrayref of options that must exist in the options
543           object.
544
545       This method returns the object for convenient chaining:
546
547          $opt = Getopt::Lucid->getopt(\@spec)->validate;
548
549   append_defaults()
550         %options = append_defaults( %config_hash );
551         %options = append_defaults( \%config_hash );
552
553       Takes a hash or hash reference of new default values, modifies the
554       stored defaults, recalculates the result of processing the command line
555       with the revised defaults, and returns a hash with the resulting
556       options.  Each key/value pair in the passed hash is added to the stored
557       defaults.  For Switch and Param options, the value in the passed hash
558       will overwrite any preexisting value.  For Counter options, the value
559       is added to any preexisting value.  For List options, the value (or
560       values, if the value is an array reference) will be pushed onto the end
561       of the list of existing values.  For Keypair options, the key/value
562       pairs will be added to the existing hash, overwriting existing
563       key/value pairs (just like merging two hashes).  Keys which are not
564       valid names from the options specification will be ignored.
565
566   defaults()
567         %defaults = $opt->defaults();
568
569       Returns a hash containing current default values.  Keys are names from
570       the option specification (without any leading dashes).  These defaults
571       represent the baseline values that are modified by the parsed command
572       line options.
573
574   getopt()
575         $opt = Getopt::Lucid->getopt( \@option_spec );
576         $opt = Getopt::Lucid->getopt( \@option_spec, \@option_array );
577         $opt->getopt();
578
579       Parses the command line array (@ARGV by default).  When called as a
580       class function, "getopt" takes the same arguments as "new", calls "new"
581       to create an object before parsing the command line, and returns the
582       new object.  When called as an object method, it takes no arguments and
583       returns itself.
584
585       For convenience, C<getopts()> is a alias for C<getopt()>.
586
587   merge_defaults()
588         %options = merge_defaults( %config_hash );
589         %options = merge_defaults( \%config_hash );
590
591       Takes a hash or hash reference of new default values, modifies the
592       stored defaults, recalculates the result of processing the command line
593       with the revised defaults, and returns a hash with the resulting
594       options.  Each key/value pair in the passed hash is added to the stored
595       defaults, overwriting any preexisting value.  Keys which are not valid
596       names from the options specification will be ignored.
597
598   names()
599         @names = $opt->names();
600
601       Returns the list of names in the options specification.  Each name
602       represents a key in the hash of options provided by "options".
603
604   options()
605         %options = $opt->options();
606
607       Returns a deep copy of the options hash.  Before "getopt" is called,
608       its behavior is undefined.  After "getopt" is called, this will return
609       the result of modifying the defaults with the results of command line
610       processing.
611
612   replace_defaults()
613         %options = replace_defaults( %config_hash );
614         %options = replace_defaults( \%config_hash );
615
616       Takes a hash or hash reference of new default values, replaces the
617       stored defaults, recalculates the result of processing the command line
618       with the revised defaults, and returns a hash with the resulting
619       options.  Each key/value pair in the passed hash replaces existing
620       defaults, including those given in the option specifications.  Keys
621       which are not valid names from the option specification will be
622       ignored.
623
624   reset_defaults()
625         %options = reset_defaults();
626
627       Resets the stored defaults to the original values from the options
628       specification, recalculates the result of processing the command line
629       with the restored defaults, and returns a hash with the resulting
630       options.  This undoes the effect of a "merge_defaults" or
631       "add_defaults" call.
632
633   usage()
634       Returns a string of usage information derived from the options spec,
635       including any "doc" modifiers.  Because invalid options throw
636       exceptions, if you want to provide usage, you should separately invoke
637       "new" and "getopt"
638
639          my $opt = Getopt::Lucid->new( \@spec );
640          eval { $opt->getopt() };
641          if ($@) {
642            print "$@\n" && print $opt->usage and exit 1
643              if ref $@ eq 'Getopt::Lucid::Exception::ARGV';
644            ref $@ ? $@->rethrow : die $@;
645          }
646

API CHANGES

648       In 1.00, the following API changes have been made:
649
650       ·   "new()" now takes an optional hashref of parameters as the last
651           argument
652
653       ·   The global $STRICT variable has been replaced with a per-object
654           parameter "strict"
655
656       ·   The "required" modifier has been removed and a new "validate"
657           method has been added to facilitate late/custom checks of required
658           options
659

SEE ALSO

661       ·   Config::Tiny
662
663       ·   Config::Simple
664
665       ·   Config::Std
666
667       ·   Getopt::Long
668
669       ·   Regexp::Common
670

BUGS

672       Please report any bugs or feature using the CPAN Request Tracker.  Bugs
673       can be submitted through the web interface at
674       <http://rt.cpan.org/Dist/Display.html?Queue=Getopt-Lucid>
675
676       When submitting a bug or request, please include a test-file or a patch
677       to an existing test-file that illustrates the bug or desired feature.
678

SUPPORT

680   Bugs / Feature Requests
681       Please report any bugs or feature requests through the issue tracker at
682       <https://github.com/dagolden/Getopt-Lucid/issues>.  You will be
683       notified automatically of any progress on your issue.
684
685   Source Code
686       This is open source software.  The code repository is available for
687       public review and contribution under the terms of the license.
688
689       <https://github.com/dagolden/Getopt-Lucid>
690
691         git clone https://github.com/dagolden/Getopt-Lucid.git
692

AUTHOR

694       David Golden <dagolden@cpan.org>
695

CONTRIBUTORS

697       ·   David Golden <xdg@xdg.me>
698
699       ·   David Precious <davidp@preshweb.co.uk>
700
701       ·   James E Keenan <jkeenan@cpan.org>
702
703       ·   Kevin McGrath <kmcgrath@cpan.org>
704
705       ·   Nova Patch <patch@cpan.org>
706
707       ·   Robert Bohne <rbo@cpan.org>
708
709       ·   thilp <thilp@thilp.net>
710
712       This software is Copyright (c) 2018 by David Golden.
713
714       This is free software, licensed under:
715
716         The Apache License, Version 2.0, January 2004
717
718
719
720perl v5.28.0                      2018-06-21                  Getopt::Lucid(3)
Impressum