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.10
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 default
171       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 default()
271       modifier or later modified with "append_defaults", "merge_defaults", or
272       "replace_defaults".  This ensures internal consistency.
273
274       If no default is explicitly provided, validation is only applied if the
275       option appears on the command line. (In other words, the built-in
276       defaults are always considered valid if the option does not appear.)
277       If this is not desired, the "required" option to the "validate" method
278       should be used to force users to provide an explicit value.
279
280          # Must be provided and is thus always validated
281          @spec = ( Param("width")->valid(qr/\d+/) );
282          $opt = Getopt::Lucid->getopt(\@spec);
283          $opt->validate( {requires => ['width']} );
284
285       For validation subroutines, the value found on the command line is
286       passed as the first element of @_, and $_ is also set equal to the
287       first element.  (N.B. Changing $_ will not change the value that is
288       captured.)  The value validates if the subroutine returns a true value.
289
290       For validation with regular expressions, consider using Regexp::Common
291       for a ready library of validation options.
292
293       Older versions of Getopt::Lucid used validation arguments provided in
294       the Spec constructor.  This is still supported, but is deprecated and
295       discouraged. It may be removed in a future version of Getopt::Lucid.
296
297          # deprecated
298          Param("height", qr/\d+/)
299
300       Options object validation
301
302       The "validate" method should be called on the result of "getopt".  This
303       will check that all parameter prerequisites defined by "needs" have
304       been met.  It also takes a hashref of arguments.  The optional
305       "requires" argument gives an arrayref of parameters that must exist.
306
307       The reason that object validation is done separate from "getopt" is to
308       allow for better control over different options that might be required
309       or to allow some dependencies (i.e. from "needs") to be met via a
310       configuration file.
311
312          @spec = (
313            Param("action")->needs(qw/user password/),
314            Param("user"),
315            Param("password"),
316          );
317          $opt = Getopt::Lucid->getopt(\@spec);
318          $opt->merge_defaults( read_config() ); # provides 'user' & 'password'
319          $opt->validate({requires => ['action']});
320
321   Parsing the Command Line
322       Technically, Getopt::Lucid scans an array for command line options, not
323       a command-line string.  By default, this array is @ARGV (though other
324       arrays can be used -- see new()), which is typically provided by the
325       operating system according to system-specific rules.
326
327       When Getopt::Lucid processes the array, it scans the array in order,
328       removing any specified command line options and any associated
329       arguments, and leaving behind any unrecognized elements in the array.
330       If an element consisting solely of two-dashes ("--") is found, array
331       scanning is terminated at that point.  Any options found during
332       scanning are applied in order.  E.g.:
333
334          @ARGV = qw( --lib /tmp --lib /var );
335          my $opt = Getopt::Lucid->getopt( [ List("lib") ] );
336          print join ", " $opt->lib;
337          # prints "/tmp, /var"
338
339       If an element encountered in processing begins with a dash, but is not
340       recognized as a short-form or long-form option name or alias, an
341       exception will be thrown.
342
343   Negation
344       Getopt::Lucid also supports negating options.  Options are negated if
345       the option is specified with "no-" or "--no-" prefixed to a name or
346       alias.  By default, negation clears the option:  Switch and Counter
347       options are set to zero; Param options are set to ""; List and Keypair
348       options are set to an empty list and empty hash, respectively. For List
349       and Keypair options, it is also possible to negate a specific list
350       element or hash key by placing an equals sign and the list element or
351       key immediately after the option name:
352
353          --no-lib=/tmp --no-define=arch
354          # removes "/tmp" from lib and the "arch" key from define
355
356       As with all options, negation is processed in order, allowing a "reset"
357       in the middle of command line processing.  This may be useful for those
358       using command aliases who wish to "switch off" options in the alias.
359       E.g, in Unix:
360
361          $ alias wibble = wibble.pl --verbose
362          $ wibble --no-verbose
363
364          # @ARGV would contain ( "--verbose", "--no-verbose" )
365
366       This also may have applications in post-processing configuration files
367       (see "Managing Defaults and Config Files").
368
369   Accessors and Mutators
370       After processing the command-line array, the values of the options may
371       be read or modified using accessors/mutators of the form "get_NAME" and
372       "set_NAME", where NAME represents the option name in the specification
373       without any leading dashes. E.g.
374
375          @spec = (
376            Switch("--test|-t"),
377            List("--lib|-L"),
378            Keypair("--define|-D"),
379          );
380
381          $opt = Getopt::Lucid->getopt( \@spec );
382          print $opt->get_test ? "True" : "False";
383          $opt->set_test(1);
384
385       For option names with dashes, underscores should be substituted in the
386       accessor calls.  E.g.
387
388          @spec = (
389            Param("--input-file|-i")
390          );
391
392          $opt = Getopt::Lucid->getopt( \@spec );
393          print $opt->get_input_file;
394
395       This can create an ambiguous case if a similar option exists with
396       underscores in place of dashes.  (E.g. "input_file" and "input-file".)
397       Users can safely avoid these problems by choosing to use either dashes
398       or underscores exclusively and not mixing the two styles.
399
400       List and Keypair options are returned as flattened lists:
401
402          my @lib = $opt->get_lib;
403          my %define = $opt->get_define;
404
405       Using the "set_NAME" mutator is not recommended and should be used with
406       caution.  No validation is performed and changes will be lost if the
407       results of processing the command line array are recomputed (e.g, such
408       as occurs if new defaults are applied).  List and Keypair options
409       mutators take a list, not references.
410
411   Managing Defaults and Config Files
412       A typical problem for command-line option processing is the precedence
413       relationship between default option values specified within the
414       program, default option values stored in a configuration file or in
415       environment variables, and option values specified on the command-line,
416       particularly when the command-line specifies an alternate configuration
417       file.
418
419       Getopt::Lucid takes the following approach to this problem:
420
421       •   Initial default values may be specified as part of the option
422           specification (using the default() modifier)
423
424       •   Default values from the option specification may be modified or
425           replaced entirely with default values provided in an external hash
426           (such as from a standard config file or environment variables)
427
428       •   When the command-line array is processed, options and their
429           arguments are stored in the order they appeared in the command-line
430           array
431
432       •   The stored options are applied in-order to modify or replace the
433           set of "current" default option values
434
435       •   If default values are subsequently changed (such as from an
436           alternative configuration file), the stored options are re-applied
437           in-order to the new set of default option values
438
439       With this approach, the resulting option set is always the result of
440       applying options (or negations) from the command-line array to a set of
441       default-values.  Users have complete freedom to apply whatever
442       precedence rules they wish to the default values and may even change
443       default values after the command-line array is processed without losing
444       the options given on the command line.
445
446       Getopt::Lucid provides several functions to assist in manipulating
447       default values:
448
449       •   merge_defaults() -- new defaults overwrite any matching, existing
450           defaults.  KeyPairs hashes and List arrays are replaced entirely
451           with new defaults
452
453       •   append_defaults() -- new defaults overwrite any matching, existing
454           defaults, except for Counter and List options, which have the new
455           defaults added and appended, respectively, and KeyPair options,
456           which are flattened into any existing default hash
457
458       •   replace_defaults() -- new defaults replace existing defaults; any
459           options not provided in the new defaults are reset to zero/empty,
460           ignoring any default given in the option specification
461
462       •   reset_defaults() -- returns defaults to values given in the options
463           specification
464
465   Exceptions and Error Handling
466       Getopt::Lucid uses Exception::Class for exceptions.  When a major error
467       occurs, Getopt::Lucid will die and throw one of three Exception::Class
468       subclasses:
469
470       •   "Getopt::Lucid::Exception::Usage" -- thrown when Getopt::Lucid
471           methods are called incorrectly
472
473       •   "Getopt::Lucid::Exception::Spec" -- thrown when the specification
474           array contains incorrect or invalid data
475
476       •   "Getopt::Lucid::Exception::ARGV" -- thrown when the command-line is
477           processed and fails to pass specified validation, requirements, or
478           is otherwise determined to be invalid
479
480       These exceptions may be caught using an "eval" block and allow the
481       calling program to respond differently to each class of exception.
482
483   Ambiguous Cases and Gotchas
484       One-character aliases and "anycase"
485
486          @spec = (
487            Counter("verbose|v")->anycase,
488            Switch("version|V")->anycase,
489          );
490
491       Consider the spec above.  By specifying "anycase" on these, "verbose",
492       "Verbose", "VERBOSE" are all acceptable, as are "version", "Version"
493       and so on.  (Including long-form versions of these, too, if "magic"
494       mode is used.)  However, what if the command line has "-v" or even "-v
495       -V"?  In this case, the rule is that exact case matches are used before
496       case-insensitive matches are searched.  Thus, "-v" can only match
497       "verbose", despite the "anycase" modification, and likewise "-V" can
498       only match "version".
499
500       Identical names except for dashes and underscores
501
502          @spec = (
503            Param("input-file"),
504            Switch("input_file"),
505          );
506
507       Consider the spec above.  These are two, separate, valid options, but a
508       call to the accessor "get_input_file" is ambiguous and may return
509       either option, depending on which first satisfies a "fuzzy-matching"
510       algorithm inside the accessor code.  Avoid identical names with mixed
511       dash and underscore styles.
512

METHODS

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

API CHANGES

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

SEE ALSO

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

BUGS

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

SUPPORT

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

AUTHOR

693       David Golden <dagolden@cpan.org>
694

CONTRIBUTORS

696       •   Chris White <cxwembedded@gmail.com>
697
698       •   David Golden <xdg@xdg.me>
699
700       •   David Precious <davidp@preshweb.co.uk>
701
702       •   James E Keenan <jkeenan@cpan.org>
703
704       •   Kevin McGrath <kmcgrath@cpan.org>
705
706       •   Nova Patch <patch@cpan.org>
707
708       •   Robert Bohne <rbo@cpan.org>
709
710       •   thilp <thilp@thilp.net>
711
713       This software is Copyright (c) 2019 by David Golden.
714
715       This is free software, licensed under:
716
717         The Apache License, Version 2.0, January 2004
718
719
720
721perl v5.38.0                      2023-07-20                  Getopt::Lucid(3)
Impressum