File Coverage

blib/lib/Getopt/Mixed/Help.pm
Criterion Covered Total %
statement 220 222 99.1
branch 137 142 96.4
condition 21 24 87.5
subroutine 18 18 100.0
pod n/a
total 396 406 97.5


line stmt bran cond sub pod time code
1             package Getopt::Mixed::Help;
2              
3             # Author, Copyright and License: see end of file
4              
5             =head1 NAME
6              
7             Getopt::Mixed::Help - combine L> with usage and help
8              
9             =head1 SYNOPSIS
10              
11             use constant DEFAULT_LOOPS => 10;
12             use Getopt::Mixed::Help
13             ('...' => 'filenames to be processed',
14             'ENV' => 'SCRIPT_OPT_',
15             'ENV_' => 'SCRIPT_OPT_',
16             'd>debug:i number' => 'turn on debugging information (*)',
17             'e>execute' => 'do it without asking for confirmation',
18             'f>force' => 'override all safety checks',
19             'i>interactive' => 'asks for confirmation before doing it',
20             'l>loops count' => 'number of loops to do',
21             'n>no-execute' => 'just print what would be done without doing it',
22             'q>quiet' => 'suppress all information',
23             's>summary' => 'print summary information on exit',
24             'v>verbose:i number' => 'turn on verbose information (*)',
25             '(*)' => '(*) You may add a positive integer for a higher level.'
26             );
27             if ($opt_...
28              
29             export SCRIPT_OPT_INTERACTIVE=1
30             test_script -d -v 2 --summary some_file.ext other_file.ext
31              
32             =head1 ABSTRACT
33              
34             Getopt::Mixed::Help is a simplified interface to Getopt::Long adding
35             usage (help) functionality. It automatically adds the options -?, -h
36             and --help (the last two configurable) to print the usage text. It
37             allows to get option values from the environment (if the operating
38             system it runs on supports environment variables). It can
39             automatically get default values from Perl constants. It can also add
40             different flavours of support for multiple options. Finally it
41             supports debugging output of the options used.
42              
43             So like Getopt::Long it is (just another) module that parses options
44             passed on the command line into variables while removing them from
45             @ARGV. Only normal parameters remain in @ARGV.
46              
47             =head1 DESCRIPTION
48              
49             The module uses a direct import mechanism called with a hash as
50             parameter. The structure of the hash is as follows:
51              
52             The key is a combined (SHORT > LONG [ARGUMENT SPECIFIER [VALUE
53             IDENTIFIER]]) option description for the outdated module
54             L>, except for the VALUE IDENTIFIER which is simply
55             included into the help text. The value following the key is simply
56             the help text for this option. The examples should make everything
57             clear even if you are not familiar with L>.
58              
59             If the second character of the first key is not C>, the first
60             key is taken as descriptive identifiers for additional parameters and
61             the help for them.
62              
63             Any key starting with C<(> and ending with C<)> will be interpreted as
64             a footnote (additional help text) to the real options. They should be
65             used at the end of the list only.
66              
67             A key equal to C is used to get default values for the remaining
68             options from the environment. For any option not initialised on the
69             command line an environment variable with the prefix of the value
70             following C and a rest of the name identical to the uppercase
71             long option name (e.g. C) will be checked. If this
72             environment variable exists, it will be used to set the option. Note
73             that in the name of the rest of the environment variable uppercase is
74             used and hyphens are relaced with underlines.
75              
76             A key equal to C is used in the same way as the key C. In
77             addition it allows for a special environment variable with the prefix
78             of the value following C followed by a single underline (C<_>) as
79             combined initialiser (for more than one option, e.g. C
80             SCRIPT_OPT__='debug verbose=2'>). Note that no whitespaces are
81             allowed in the values of the options initialised this way as the
82             string in the environment variable is parsed in a simple way.
83              
84             The module defines the variable $optUsage containing the complete help
85             text.
86              
87             If an option C exists and is choosen on the command line, this
88             module will print all option values and all remaining parameters to
89             standard error. The name of this option may be changed, see
90             C<"changing the debug option"> below in the L
91             BEHAVIOUR"> section.
92              
93             Perl constants with the prefix C and a name matching the
94             option are used as default values for the options, see below for
95             details.
96              
97             =head1 EXPORT
98              
99             The module automatically exports all option variables (C<$opt_>) as
100             well as the usage text (C<$optUsage>).
101              
102             =head1 OPTION DETAILS
103              
104             =head2 parameter help ('parameter text' => 'parameter description')
105              
106             If a script takes normal parameters (as oposed to options starting
107             with a hyphen), their description for the help text must be the first
108             parameter of the hash passed on import. It is also necessary that the
109             second character of the key is not C>. An example, if a script
110             using this module accepts one or more filenames as parameters, you
111             might want to use the following import parameter:
112              
113             '...' => 'filenames to be processed'
114              
115             This would produce the following help text:
116              
117             usage: script.pl [] [--] ...
118              
119             filenames to be processed
120              
121             =head2 combined options ('o>long-option ...' => 'option description')
122              
123             Combined options are options that allow to use both a long and a short
124             option to set the same option variable for a script (see
125             L> for details). In principle Getopt::Mixed::Help
126             uses a syntax similar to L> for the key of the import
127             parameter, but it changes their sequence within the alias. The
128             minimal key for the import parameter just uses the character of the
129             short option followed by C> followed by the long option (without
130             C<-->). It would define a boolean option variable, for example the
131             import parameter
132              
133             'o>long-option' => 'some long option'
134              
135             defines a boolean option with the identifier C<$opt_long_option> that
136             can be set with the short option C<-o> and the long option
137             C<--long-option> (which may be abbreviated as described in
138             L>). Its help text would look as follows:
139              
140             -o|--long-option
141             some long option
142              
143             For string, integer or real number options the key of the import
144             parameter must be extended with an argument specifier. There are 6
145             possible argument specifiers:
146              
147             =s for a mandatory string argument
148             =i for a mandatory integer argument
149             =f for a mandatory real number argument
150             :s for an optional string argument
151             :i for an optional integer argument
152             :f for an optional real number argument
153              
154             The argument specifieres may be followed by a blank and the value
155             identifier, a short text describing the argument. This text will
156             become part of the help text. If no describing text is specified,
157             C will be used for strings, C for integers and
158             C for real numbers. Consider the import parameters of the
159             following example:
160              
161             'd>directory=s directory' => 'name of the directory',
162             'o>offset:f' => 'offset in the file in % (default 0.0)'
163              
164             This defines a string option with a mandatory value and the
165             indentifier C<$opt_directory> as well as a real number option with an
166             optional value and the identifier C<$opt_offset>. The help text for
167             these options would be:
168              
169             -d|--directory
170             name of the directory
171             -o|--offset []
172             offset in the file in % (default 0.0)
173              
174             For an optional value the default value that is used if no value is
175             specified depends on its type. For strings it is an empty string
176             (C<''>), for integers it is 1 and for real numbers it is 0.0.
177              
178             =head2 long options ('long-option ...' => 'option description')
179              
180             If you run out of characters for short options you end up with the
181             need for options that only exist as a long option. They are just
182             declared like the combined options without the leading short option
183             character and the C>, e.g.
184              
185             'long-optional-string:s' => 'optional string'
186              
187             The only pitfall with long options comes when the first option you
188             declare is not a combined option and you don't have normal parameters
189             as Getopt::Mixed::Help then would treat your long option declaration
190             as a L. To avoid this just put a C<-E->
191             declaration before it (see C in L
192             BEHAVIOUR"> below).
193              
194             =head2 getting options from environment variables ('ENV' => 'SCRIPT_OPT_')
195              
196             There are two special import parameter keys that allow your script to
197             be able to read options from environment variables (if your operating
198             system supports it).
199              
200             The first key is the string C<'ENV'>. If it is defined, each option
201             variable cat get its default value from an environment variable if
202             that environment variable is set. The name of that environment
203             variable is composed of the value of the C<'ENV'> import parameter and
204             the name of the long option where all characters are turned into
205             uppercase and all hyphens are replaces with underscores, e.g. for the
206             import parameters
207              
208             'ENV' => 'MYSEARCH',
209             'd>start-dir=s directory' => 'name of the first directory'
210              
211             the option variable C<$opt_start_dir> will be filled with the value of
212             the environment variable MYSEARCHSTART_DIR if that is set and the
213             option is not set on the command line.
214              
215             The second environment import parameter key is the string C<'ENV_'>.
216             It works similar to the other one except that it defines an
217             environment variable that can be used to set a whole default command
218             line at once (well, only its options and not if their values would
219             contain blanks). For this key the name of that environment variable
220             is composed of the value of the C<'ENV_'> import parameter followed by
221             an underscore (C<_>). To put several long options into the
222             environment variable so created, just concatenate them together with
223             blanks and without their leading C<-->. If for example above's
224             directory and offset options are preceeded by
225              
226             'ENV_' => 'MYSEARCH'
227              
228             you could set the environment variable MYSEARCH_ from a shell like
229             this:
230              
231             export MYSEARCH_='offset=12.5 directory=/tmp/somewhere'
232              
233             But remember, this works for simple things only, for more complicated
234             defaults from the environment you must create one variable for each
235             option as described above. If you do both the value of the specific
236             environment variable overwrites that of the combined one.
237              
238             And a warnings for this features, if you use both environment import
239             parameters (which is quite reasonable) you must use the same value for
240             both of them, otherwise only the last one specified works.
241              
242             =head2 footnotes
243              
244             Sometimes you'll like to describe an option in more details, want to
245             give additional information concerning more than one option or just
246             like to add some more text at the end of a generated help. To do
247             that, Getopt::Mixed::Help allows you to add just about any text you
248             like to your import parameter list using keys that begin and end in
249             parentheses. The key is not used any further, so you can use any text
250             as long as you put it into parentheses. The text of the description
251             is put into the help text as it is, but preceeded and followed by a
252             newline.
253              
254             Normally all footnotes are put at the end of the option list but
255             theoretically you could also put one in-between to split the option
256             list into two (or more) parts - the footnote is put into the help text
257             just where it occurs.
258              
259             =head1 DEFINING DEFAULT VALUES USING PERL CONSTANTS
260              
261             If you define a Perl constant (C) beginning with
262             C and ending with the name of the long option where all
263             characters are turned into uppercase and all hyphens are replaces with
264             underscores, e.g. for the import parameters
265              
266             'd>start-dir=s directory' => 'name of the first directory'
267              
268             a
269              
270             use constant DEFAULT_START_DIR => '.';
271              
272             the variable C<$opt_start_dir> will be initialised, if no other value
273             is specified by environment variable or on the command line. (Options
274             on the command line overrule the values specified in environment
275             variables, which themselves overrule the default values of the Perl
276             constants.)
277              
278             In addition the default value will also be added to the help text for
279             that option. The additional text will be put into parentheses and
280             starts with the words C. See below how to change that.
281              
282             Note that all Perl constants with default values must be defined
283             before the C command including this module, otherwise they have
284             no effect. Also note that they must belong to the C
285             namespace. And finally note that only simple values and array
286             references are supported yet.
287              
288             =head1 CHANGING DEFAULT BEHAVIOUR
289              
290             Some declarations looking like silly declarations (they all start with
291             a hyphen as the short option character) can change the behaviour of
292             the module.
293              
294             =head2 separator ('->-' => '')
295              
296             The separator is only needed if you don't have normal parameters and
297             your first option only comes in a long form, e.g. like in
298              
299             '->-' => '', 'long-optional-string:s' => 'optional string'
300              
301             which produces the following help text:
302              
303             usage: script.pl [] [--]
304              
305             options: --long-optional-string []
306             optional string
307              
308             Instead of the separator any of the other behavior changing
309             declarations will have the same effect.
310              
311             =head2 changing the help option ('->help' => 'H>Hilfe')
312              
313             With C<-Ehelp> you can replace the default names C (as short
314             option) and C (as long option) of the help options. The value
315             part of this declaration must contain the new short option character
316             followed by C> followed by the long option (without C<-->) as in
317             a normal boolean option declaration.
318              
319             Note that C<-?> will always remain as help option as well and can not
320             be renamed or removed!
321              
322             =head2 changing the debug option ('->debug' => 'verbose')
323              
324             With C<-Edebug> you can replace the default (long option) name
325             C of the debug option. (Remember that the module prints all
326             options on STDERR if a long option called C is declared and
327             set.) The value part of this declaration is just the new long option
328             name (without C<-->).
329              
330             Note that the debugging option still has to be declared as normal
331             option as well.
332              
333             =head2 changing the usage text ('->usage' => 'use as')
334              
335             With this modifying option you can replace the text C at the
336             beginning of the help text with the string specified in the value part
337             of this declaration.
338              
339             Note that the variable used for the help text is still called
340             C<$optUsage>.
341              
342             =head2 changing the options text ('->options' => 'switches')
343              
344             With this modifying option you can replace the text C in the
345             help text with the string specified in the value part of this
346             declaration. Note that the string occurs two times.
347              
348             Due to the way the help text is constructed this option has to be
349             specified before the first normal option of the import (use)
350             statement!
351              
352             =head2 changing the default value text ('->default' => ' (init. %s)')
353              
354             With this modifying option you can replace the text appended for
355             options with default values set by Perl constant (C< (defaults to
356             %s)>) in the help text with the string specified in the value part of
357             this declaration. Note that the string must contain a C<%s> as it is
358             put together with C (see L). You may also
359             set this modifying option to C to disable the additional help
360             text.
361              
362             Due to the way the help text is constructed this option has to be
363             specified before the first normal option of the import (use)
364             statement!
365              
366             =head2 enabling multiple support ('->multiple' => ...)
367              
368             This neat modifying option gives you support to process multiple
369             occurances of the same option. It comes in two flavours, depending on
370             the value part of the declaration:
371              
372             =head3 multiple support using concatenation ('->multiple' => 'text')
373              
374             With this flavour multiple occurances of the same option are (sort of)
375             concatenated. The kind of C depends on the type of the
376             option: string options are concatenated (joined) with the given text
377             put between each occurance, integers and floats are added together and
378             boolean are just counted.
379              
380             If you take the following example declaration of import parameters
381              
382             '->multiple' => ', ',
383             'd>directory=s directory' => 'name of the directory',
384             'o>offset:f' => 'offset in the file in % (default 0.0)'
385              
386             and call the script using them with a command line like:
387              
388             -d a --offset -o=0.25 -d b -d=c -o=0.33
389              
390             Now your option variable C<$opt_directory> will be set to C
391             and your option variable C<$opt_offset> will be set to the value 0.58
392             (0.0 + 0.25 + 0.33).
393              
394             Note that an empty string is a valid input for this flavour of
395             multiple occurances, the strings then are just concatenated without
396             anything between them.
397              
398             =head3 multiple support using arrays ('->multiple' => undef)
399              
400             With this flavour (yes, this one uses an explicit C value to
401             distinguish it from the last one) each option passed more than once
402             will not be returned in a normal scalar variable but in a reference to
403             an array.
404              
405             For example take the declaration from the C flavour and
406             just replace the value part C<', '> with C. If you use this
407             with the following options on your command line:
408              
409             -d a -o 0.25 --directory=b
410              
411             This time your option variable C<$opt_offset> will be a scalar with
412             the value 0.25 but the option variable C<$opt_directory> will be a
413             reference to an array containing the values C and C (in that
414             sequence).
415              
416             It is up to you to handle the different variable types adequately!
417             (But it is guaranteed that a C will either return C<''> or
418             C<'ARRAY'>.)
419              
420             =head2 multiple per option support using arrays
421              
422             A third method to support multiple options, again as arrays but only
423             for selected options works by slightly modifying their import
424             parameter key using a double CE>. So suppose you have the
425             following import parameters (without any C<-Emultiple> option at
426             all):
427              
428             'd>>directory=s directory' => 'name of the directory',
429             'o>offset:f' => 'offset in the file in % (default 0.0)'
430              
431             If you now call your script with
432              
433             -d a -o0.25 --directory=b -o0.5
434              
435             you'll end up with the value 0.5 in C<$opt_offset> and a reference to
436             an array with C and C in C<$opt_directory>. So this gives you
437             an easy way to enable multiple option support just for selected
438             options easing the overhead for analysing all of them to be possible
439             array references.
440              
441             For long options (without a character for a short option) you just
442             start them with the double CE>.
443              
444             Multiple options as string on a per-option-base is not supported, but
445             you can get that with short statement like the following:
446              
447             $opt_directory = join(' ', @$opt_directory)
448             if ref($opt_directory) eq 'ARRAY';
449              
450             =head1 FUNCTIONS
451              
452             =cut
453              
454             #########################################################################
455              
456 14     14   105660 use 5.006;
  14         66  
  14         956  
457 14     14   86 use strict;
  14         26  
  14         495  
458 14     14   90 use warnings;
  14         43  
  14         439  
459              
460 14     14   81 use Carp;
  14         28  
  14         1589  
461 14     14   81 use File::Basename;
  14         27  
  14         1783  
462 14         99 use Getopt::Long qw(:config posix_default no_ignore_case bundling_override
463 14     14   25016 );
  14         308190  
464             # debug);
465              
466             #******************************************************************
467              
468 14     14   3751 use vars '$optUsage';
  14         25  
  14         907  
469              
470             our $VERSION = '0.26';
471              
472             # default strings (they are the ones used for indent!):
473 14     14   73 use constant DEFAULT_USAGE => 'usage';
  14         21  
  14         881  
474 14     14   64 use constant DEFAULT_OPTIONS => 'options';
  14         31  
  14         600  
475 14     14   78 use constant DEFAULT_DEFAULT => ' (defaults to %s)';
  14         27  
  14         9120  
476              
477             #########################################################################
478              
479             =head2 B - main and only function
480              
481             see above in the main documentation how to use it
482              
483             One confession about the internals, this function doesn't use a real
484             hash; it just uses the same syntax as it really expects an array of
485             pairs (as most of you might have guessed already ;-).
486              
487             =cut
488              
489             # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
490             sub import
491             {
492 117     117   10486892 local $_;
493 117         343 my $this = shift;
494 117 100       695 croak 'bad usage of ', __PACKAGE__ unless $this eq __PACKAGE__;
495 116 100       617 croak 'no parameter passed to ', __PACKAGE__ unless 0 < @_;
496 114 100       619 croak 'unbalanced parameter list passed to ', __PACKAGE__
497             unless @_ % 2 == 0;
498 112         1942 my %env = %ENV;
499              
500 112         392 my $usage_text = DEFAULT_USAGE;
501 112         166 my $options_text = DEFAULT_OPTIONS;
502 112         420 my $indent_opt1 = $options_text.': ';
503 112         790 my $indent_opt2 = ' ' x (length($options_text) + 3);
504 112         685 my $indent_help = ' ' x (length($options_text) + 7);
505 112         480 my $default_template = DEFAULT_DEFAULT;
506              
507 112         189 $optUsage = '';
508             # check/support commandline parameters that are NOT options:
509 112         163 my $has_only_options = 1;
510 112 100 100     949 if ($_[0] =~ m/^.[^>].*$/ and $_[0] ne 'ENV' and $_[0] ne 'ENV_')
      100        
511             {
512 33         138 $optUsage .= ' '.(shift)."\n\n".(shift);
513 33         68 $has_only_options = 0;
514             }
515 112         209 $optUsage .= "\n\n";
516              
517 112         170 my $help_long = 'help';
518 112         237 my $help_opt_name = 'opt_help';
519 112         153 my $help_options = 'help|h|?+';
520 112         162 my $debug_opt_name = 'opt_debug';
521              
522 112         179 my @options = ();
523 112         152 my @option_vars = ();
524 112         186 my %default_value = ();
525 112         158 my %option_type = ();
526 112         139 my %optional_integers = ();
527 112         151 my %optional_floats = ();
528 112         130 my $max_length = 0;
529 112         142 my $env_prefix = undef;
530 112         140 my $use_multiple = 0;
531 112         162 my $multiple = undef;
532 112         175 my %multiple_options = ();
533 112         713 my $package = (caller)[0];
534              
535             # preparation loop (module parameters):
536 112         348 while (@_ > 0)
537             {
538 462         611 my $option = shift;
539 462 100       9276 if ($option =~
    100          
    100          
    100          
    100          
    100          
    100          
    100          
    100          
    100          
    100          
540             m/^(?:(\w)?>(>)?)?([-a-z0-9]{2,})(?:([:=][isf])\s*(.*))?$/)
541             {
542 339         1634 my ($short_option, $is_multiple, $long_option, $specifier,
543             $opt_valtext) = ($1, $2, $3, $4, $5);
544 339         682 my $var = 'opt_'.$long_option;
545 339         1827 $var =~ s/\W/_/g;
546 339         483 my $default_text = '';
547             {
548 339         523 my $default_constant = 'DEFAULT_'.uc($long_option);
  339         750  
549 339         1107 $default_constant =~ s/\W/_/g;
550 14     14   106 no strict 'refs';
  14         68  
  14         513  
551 14     14   72 no warnings 'once';
  14         23  
  14         7949  
552 339         419 my $default_cref = *{$package.'::'.$default_constant}{CODE};
  339         1409  
553 339 100       1047 if ( ref($default_cref) eq 'CODE')
554             {
555 6 100       33 if (ref(&$default_cref) eq '')
    100          
556             {
557 3         14 $default_text =
558             sprintf($default_template, &$default_cref);
559             }
560             elsif (ref(&$default_cref) eq 'ARRAY')
561             {
562 2         18 $default_text =
563             sprintf($default_template,
564 2         4 join(', ', @{&$default_cref}));
565             }
566             else
567             {
568 1         199 croak(ref(&$default_cref), ' constants as ',
569             'default values are not yet supported in ',
570             __PACKAGE__);
571             }
572 5         22 $default_value{$var} = &$default_cref;
573             }
574             }
575 338 100       812 $specifier = '' unless defined $specifier;
576 338 100 100     3004 if ($opt_valtext and $specifier =~ m/^=/)
    100 66        
    100          
    100          
    50          
577             {
578 6 100       20 if ($opt_valtext =~ m/^{.*}$/)
579             {
580 1         3 $opt_valtext = ' '.$opt_valtext;
581             }
582             else
583             {
584 5         13 $opt_valtext = ' <'.$opt_valtext.'>';
585             }
586             }
587             elsif ($opt_valtext and $specifier =~ m/^:/)
588             {
589 3         10 $opt_valtext = ' [<'.$opt_valtext.'>]';
590             }
591             elsif ($specifier =~ m/^=/)
592             {
593 128 50       656 $opt_valtext = ($specifier =~ m/i$/ ? ' ' :
    100          
    100          
594             $specifier =~ m/s$/ ? ' ' :
595             $specifier =~ m/f$/ ? ' ' : ' ');
596             }
597             elsif ($specifier =~ m/^:/)
598             {
599 153 50       940 $opt_valtext = ($specifier =~ m/i$/ ? ' []' :
    100          
    100          
600             $specifier =~ m/s$/ ? ' []' :
601             $specifier =~ m/f$/ ? ' []' :
602             ' []');
603             }
604             elsif (defined $opt_valtext)
605             {
606 0         0 die 'internal inconsistency: specifierless value text in ',
607             $option
608             }
609             else
610             {
611 48         92 $opt_valtext = '';
612             }
613 338 100       787 $optUsage .= 0 == @option_vars ? $indent_opt1 : $indent_opt2;
614 338 100       916 $optUsage .= '-'.$short_option.'|' if defined $short_option;
615 338         593 $optUsage .= '--'.$long_option.$opt_valtext."\n";
616 338         888 $optUsage .= $indent_help.(shift).$default_text."\n";
617 338         521 my $option_key = $long_option;
618 338 100       1139 $option_key .= '|'.$short_option if defined $short_option;
619             # fix default numeric values of optional integer parameters:
620 338 100       673 $option_key .= $specifier eq ':i' ? ':+' : $specifier;
621             {
622 14     14   81 no strict 'refs';
  14         24  
  14         16456  
  338         341  
623 338         558 push @options, $option_key, *{$var}{SCALAR};
  338         1489  
624             }
625 338         680 push @option_vars, $var;
626 338         665 $option_type{$var} = $specifier;
627 338         1235 $option_type{$var} =~ s/[:=]//;
628 338 100       844 $max_length = length($var) if $max_length < length($var);
629 338 100       3743 if ($is_multiple)
630             {
631 9 100       182 croak('multiple option support per option and per global',
632             ' flag is mutually exclusive in ', __PACKAGE__)
633             if $use_multiple;
634 8         13 $options[-2] .= '@';
635 8         243 $multiple_options{$var} = $long_option;
636             }
637             # Undefined optional options must be defaulted to undef to
638             # distinguish them from the default value "empty string":
639 337 100       2455 if ($specifier =~ m/^:i$/)
    100          
640             {
641 40         167 $optional_integers{$var} = 1;
642             }
643             elsif ($specifier =~ m/^:f$/)
644             {
645 40         168 $optional_floats{$var} = 0.0;
646             }
647             }
648              
649             elsif ($option =~ m/^\(.+\)$/)
650             {
651 32         137 $optUsage .= "\n".(shift)."\n";
652             }
653             elsif ($option eq '->-')
654             {
655 4         12 shift;
656             }
657             elsif ($option eq '->debug')
658             {
659 2         14 $_ = shift;
660 2 100       120 m/^([-a-z0-9]{2,})$/i or
661             croak 'bad renaming of debug in ', __PACKAGE__;
662 1         4 $debug_opt_name = 'opt_'.$1;
663             }
664             elsif ($option eq '->default')
665             {
666 2         6 $_ = shift;
667 2 100       134 m/%s/i or
668             croak 'default text must contain %s in ', __PACKAGE__;
669 1         4 $default_template = $_;
670             }
671             elsif ($option eq '->help')
672             {
673 3         30 $_ = shift;
674 3 100       145 m/^(\w)>([-a-z0-9]{2,})$/i or
675             croak 'bad renaming of help in ', __PACKAGE__;
676 2         6 $help_long = $2;
677 2         6 $help_opt_name = 'opt_'.$2;
678 2         9 $help_options = $2.'|'.$1.'|?+';
679             }
680             elsif ($option eq '->multiple')
681             {
682 10 100       595 croak('multiple option support per option and per global',
683             ' flag is mutually exclusive in ', __PACKAGE__)
684             if 0 < (my @list = %multiple_options);
685 9         17 $use_multiple = 1;
686 9         30 $multiple = shift;
687             }
688             elsif ($option eq '->options')
689             {
690 1         3 $options_text = shift;
691 1         2 $indent_opt1 = $options_text.': ';
692 1         4 $indent_opt2 = ' ' x (length($options_text) + 3);
693 1         5 $indent_help = ' ' x (length($options_text) + 7);
694             }
695             elsif ($option eq '->usage')
696             {
697 1         4 $usage_text = shift;
698             }
699             elsif ($option eq 'ENV')
700             {
701 33         102 $env_prefix = shift;
702             }
703             elsif ($option eq 'ENV_')
704             {
705 33         55 $env_prefix = shift;
706 33 100       196 if (defined $env{$env_prefix.'_'})
707             {
708 4         19 foreach (split(/\s+/, $env{$env_prefix.'_'}))
709             {
710 7         26 s/^([-_a-z0-9]{2,})=?//;
711 7         24 (my $env_var = $env_prefix.uc($1)) =~ tr/-/_/;
712 7 100       47 $env{$env_var} = $_ ne '' ? $_ : 1
    100          
713             unless defined $env{$env_var};
714             }
715             }
716             }
717             else
718             {
719 2         235 croak 'bad option ', $option, ' passed to ', __PACKAGE__;
720             }
721             }
722             # for global multiple set-up using arrays:
723 104 100       261 if ($use_multiple)
724             {
725 8         30 for ($_ = 0; $_ < $#options; $_ += 2)
726             {
727 65         116 $options[$_] =~ s/:\+/:i/;
728 65 100       198 if ($options[$_] =~ m/[:=][fis]$/)
729             {
730 56         165 $options[$_] .= '@';
731             }
732             else
733             {
734 9         40 $options[$_] .= ':+';
735             }
736             }
737             }
738             # finish help text:
739             $optUsage =
740 104         4653 $usage_text.': '.basename($0).' [<'.$options_text.'>] [--]'.$optUsage;
741              
742             {
743 14     14   101 no strict 'refs';
  14         26  
  14         2669  
  104         177  
744 104         147 unshift @options, $help_options, *{$help_opt_name}{SCALAR};
  104         407  
745             }
746 104 100       458 unless (GetOptions(@options))
747             {
748 2         1323 $_ = $0;
749 2         8 s|.*/||;
750 2         34 print STDERR "Try `$_ --$help_long' for more information.\n";
751 2         2698 exit 1;
752             }
753              
754 14     14   73 no strict 'refs';
  14         28  
  14         557  
755 14     14   69 no warnings 'once';
  14         25  
  14         7069  
756 102 100 100     62777 if ($$help_opt_name or ($has_only_options and 0 <= $#ARGV))
      66        
757             {
758 5         370 print STDERR $optUsage; exit -1;
  5         6029  
759             }
760              
761             # handle concatenated multiples:
762 97 100       361 if ($use_multiple)
763             {
764 8 100       26 if (defined $multiple)
765             {
766 5         94 foreach my $option (@option_vars)
767             {
768 41 100       178 next unless defined $$option;
769 37 100       109 next unless ref($$option) eq 'ARRAY';
770 32 100 66     137 if ($option_type{$option} eq 's')
    50          
771             {
772 14         63 $$option = join($multiple, @$$option);
773             }
774             elsif ($option_type{$option} eq 'i' or
775             $option_type{$option} eq 'f')
776             {
777 18         25 my $sum = 0;
778 18         94 $sum += $_ foreach @$$option;
779 18         57 $$option = $sum;
780             }
781             else
782             {
783 0         0 die 'internal inconsistency: $option_type{$option} is ',
784             $option_type{$option};
785             }
786             }
787             }
788             # support for multiple options, array flavour:
789             else
790             {
791 3         9 foreach my $option (@option_vars)
792             {
793 24 100       68 next unless $option_type{$option} eq '';
794             next # paranoia check, this should never occur!
795 3 50       14 if ref($$option) ne '';
796 3 100       11 next if $$option == 1;
797 2         9 $_ = [ (1) x $$option ];
798 2         14 $$option = $_;
799             }
800             }
801             }
802              
803             # get defaults from environment, if applicable:
804 97 100       214 if (defined $env_prefix)
805             {
806             # set default values, if not overwritten:
807 31         81 foreach (@option_vars)
808             {
809 241 100       693 next if defined $$_;
810 98         214 my $env_var = $env_prefix.uc(substr($_, 4));
811 98 100       254 $$_ = $env{$env_var} if defined $env{$env_var};
812             }
813             }
814              
815             # get defaults from constants:
816 97         277 foreach (keys %default_value)
817             {
818 5 100       15 next if defined $$_;
819 4         12 $$_ = $default_value{$_};
820             }
821              
822             # declare main option variables and export local option variables to it:
823 97         141 *{$package.'::optUsage'} = \$optUsage;
  97         329  
824             {
825 14     14   83 no warnings "once"; # disable "GMH::opt_ ... used only once" warning
  14         575  
  14         13780  
  97         243  
826 97         152 foreach (@option_vars)
827             {
828             # single element arrays become scalars instead:
829 308 100 100     1067 if (ref($$_) eq 'ARRAY' and 1 == @$$_)
830             {
831 11         25 *{$package.'::'.$_} = \$$_->[0];
  11         41  
832             }
833             else
834             {
835 297         563 *{$package.'::'.$_} = \$$_;
  297         932  
836             }
837             }
838             }
839              
840             # print debug info, if $opt_debug is used:
841 97 100       1114 if ($$debug_opt_name)
842             {
843 5         473 print STDERR $indent_opt1, "\n";
844 5         18 foreach (@option_vars)
845             {
846 31 100       2720 print(STDERR
    100          
    100          
847             $indent_opt2, '$', $_, ':',
848             (' ' x ( $max_length - length($_) + 1 )),
849             (! defined $$_ ? 'undef' :
850             ref($$_) eq 'ARRAY'
851             ? '('.join(', ', @$$_).')'
852             : $$_ =~ m/^-?\d+(?:\.\d+)?$/ ? $$_ : '"'.$$_.'"'),
853             "\n");
854             }
855 5 100       65 print STDERR "parameter:\n" if @ARGV;
856             print STDERR $indent_opt2,
857             ($_ =~ m/^-?\d+(?:\.\d+)?$/ ? $_ : '"'.$_.'"'), "\n"
858 5 100       26025 foreach (@ARGV);
859             }
860             }
861             1;
862              
863             #******************************************************************
864              
865             __END__