File Coverage

blib/lib/Getopt/Euclid.pm
Criterion Covered Total %
statement 618 656 94.2
branch 232 274 84.6
condition 58 80 72.5
subroutine 60 62 96.7
pod 7 7 100.0
total 975 1079 90.3


line stmt bran cond sub pod time code
1             package Getopt::Euclid;
2              
3 65     65   11142190 use version; our $VERSION = version->declare('0.4.5');
  65         219070  
  65         537  
4              
5 65     65   7011 use warnings;
  65         270  
  65         2304  
6 65     65   8299 use strict;
  65         134  
  65         2182  
7 65     65   1725 use 5.005000; # perl 5.5.0
  65         1479  
  65         2957  
8 65     65   542 use Carp;
  65         168  
  65         7108  
9 65     65   98378 use Symbol ();
  65         79977  
  65         2309  
10 65     65   2529 use re 'eval'; # for matcher regex
  65         125  
  65         8319  
11 65     65   100196 use Pod::Select;
  65         188851  
  65         17135  
12 65     65   81706 use Pod::PlainText;
  65         1103888  
  65         19764  
13 65     65   1153 use File::Basename;
  65         157  
  65         7298  
14 65     65   108088 use File::Spec::Functions qw(splitpath catpath catfile);
  65         64781  
  65         7200  
15 65     65   458 use List::Util qw( first );
  65         133  
  65         8587  
16 65     65   100567 use Text::Balanced qw(extract_multiple extract_bracketed extract_variable extract_delimited);
  65         4541490  
  65         239184  
17              
18              
19             # Set some module variables
20             my $skip_keyword = 'Getopt::Euclid'; # Ignore files with a first line containing this keyword.
21             my $pod_file_msg = "# This file was generated dynamically by $skip_keyword. Do not edit it.";
22              
23             my $has_run = 0;
24             my $has_processed_pod = 0;
25             my $export_lvl = 1;
26             my @pod_names;
27             my $minimal_keys;
28             my $vars_prefix;
29             my $defer = 0;
30             my $matcher;
31             my %requireds;
32             my %options;
33             my %longnames;
34             our $man; # --man message
35             my $help; # --help message
36             my $usage; # --usage message
37             my $version; # --version message
38              
39             my $optional_re;
40             $optional_re = qr{ \[ [^[]* (?: (??{$optional_re}) [^[]* )* \] }xms;
41              
42              
43             # Global variables
44             our $SCRIPT_NAME;
45             our $SCRIPT_VERSION; # for ticket # 55259
46              
47              
48             # Convert arg specification syntax to Perl regex syntax
49              
50             my %std_matcher_for = (
51             integer => '[+-]?\\d+(?:[eE][+]?\d+)?',
52             number => '[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\d+)?',
53             input => '\S+',
54             output => '\S+',
55             string => '\S+',
56             q{} => '\S+',
57             );
58              
59             _make_equivalent(
60             \%std_matcher_for,
61             integer => [qw( int i +int +i 0+int 0+i +integer 0+integer )],
62             number => [qw( num n +num +n 0+num 0+n +number 0+number )],
63             input => [qw( readable in )],
64             output => [qw( writable writeable out )],
65             string => [qw( str s )],
66             );
67              
68             my %std_constraint_for = (
69             'string' => sub { 1 }, # Always okay (matcher ensures this)
70             'integer' => sub { 1 }, # Always okay (matcher ensures this)
71             '+integer' => sub { $_[0] > 0 },
72             '0+integer' => sub { $_[0] >= 0 },
73             'number' => sub { 1 }, # Always okay (matcher ensures this)
74             '+number' => sub { $_[0] > 0 },
75             '0+number' => sub { $_[0] >= 0 },
76             'input' => sub { $_[0] eq '-' || -r $_[0] },
77             'output' => sub {
78             my ( $vol, $dir ) = splitpath( $_[0] );
79             $dir = ($vol && $dir) ? catpath($vol, $dir) : '.';
80             $_[0] eq '-' ? 1 : -e $_[0] ? -w $_[0] : -w $dir;
81             },
82             );
83              
84             _make_equivalent(
85             \%std_constraint_for,
86             'integer' => [qw( int i )],
87             '+integer' => [qw( +int +i )],
88             '0+integer' => [qw( 0+int 0+i )],
89             'number' => [qw( num n )],
90             '+number' => [qw( +num +n )],
91             '0+number' => [qw( 0+num 0+n )],
92             'string' => [qw( str s )],
93             'input' => [qw( in readable )],
94             'output' => [qw( out writable writeable )],
95             );
96              
97              
98             sub Getopt::Euclid::Importer::DESTROY {
99 0 0 0 0   0 return if $has_run || $^C; # No errors when only compiling
100 0         0 croak '.pm file cannot define an explicit import() when using Getopt::Euclid';
101             }
102              
103              
104             sub import {
105 69     69   1839 shift @_;
106 69   100     252 @_ = grep { !( /:minimal_keys/ and $minimal_keys = 1 ) } @_;
  11         128  
107 69   66     206 @_ = grep { !( /:vars(?:<(\w+)>)?/ and $vars_prefix = $1 || 'ARGV_' ) } @_;
  6         91  
108 69   100     172 @_ = grep { !( /:defer/ and $defer = 1 ) } @_;
  4         46  
109 69         698 croak "Unknown mode ('$_')" for @_;
110 68 100       312 $export_lvl++ if not $defer;
111              
112             # No POD parsing and argument processing in Perl compile mode (ticket 34195)
113 68 100       579 return if $^C;
114              
115             # Get name of caller program and its modules in @pod_names
116 67 100       241 return unless _get_pod_names();
117              
118             # Extract POD of given files
119 63         606 __PACKAGE__->process_pods( [reverse @pod_names] );
120 63         1303 undef @pod_names;
121 63         156 $has_run = 1;
122              
123             # Parse POD + parse and export arguments
124              
125             ######
126             #use Data::Dumper; print "ARGV: ".Dumper(\@ARGV);
127             ######
128              
129 63 100       1084 __PACKAGE__->process_args( \@ARGV ) unless $defer;
130              
131 36         7554 return 1;
132             }
133              
134              
135             sub process_pods {
136             # Extract POD content from list of Perl scripts (.pl) and modules (.pm) and
137             # their corresponding .pod file if available. When given the argument
138             # {-strict => 1}, do not look for .pod files.
139 64     64 1 1990 my ($self, $perl_files, $args) = @_;
140              
141 64         147 my $pod_string = '';
142 35 50   35   40947 open my $pod_fh, '>', \$pod_string
  35         438  
  35         898  
  64         2417  
143             or croak "Could not open filehandle to variable because $!";
144 64         2831291 for my $perl_file (@$perl_files) {
145              
146 67         186 my $got_pod_file = 0;
147              
148 67 50       394 if ( not $args->{-strict} ) {
149              
150             # Find corresponding .pod file
151 67         5790 my ($name_re, $path, $suffix) = fileparse($perl_file, qr/\.[^.]*/);
152 67         919 my $pod_file = catfile( $path, $name_re.'.pod' );
153              
154             # Get POD either from .pod file (preferably) or from Perl file
155 67 100       1998 if ( -e $pod_file ) {
156             # Get .pod file content
157 6 50       247 open my $in, '<', $pod_file
158             or croak "Could not open file $pod_file because $!";
159 6         93 my $first_line = <$in>;
160 6         22 chomp $first_line;
161 6 100       96 if ( not ($first_line =~ m/$skip_keyword/) ) {
162             # Skip G::E auto-generated files since they lack important data
163 4         23 print $pod_fh "$first_line\n";
164 4         244 print $pod_fh $_ while <$in>;
165 4         11 $got_pod_file = 1;
166             }
167 6         88 close $in;
168             }
169             }
170              
171 67 100       308 if (not $got_pod_file) {
172             # Parse POD content of Perl file
173 63         590 podselect( {-output => $pod_fh}, $perl_file );
174             }
175 67 100       368453 print $pod_fh "\n" if $pod_string;
176              
177             }
178 64         930 close $pod_fh;
179 64         239 $man = $pod_string;
180 64         526 return 1;
181             }
182              
183              
184             sub process_args {
185             # First, parse the POD specifications. Then, parse the given array of
186             # arguments (\@ARGV or other) and populate %ARGV (or export specific
187             # variable names).
188 70     70 1 40742 my ($self, $args, $options) = @_;
189              
190             # Parse POD
191 70 100       327 if (not $has_processed_pod) {
192 64         308 _parse_pod();
193 51         347 $has_processed_pod = 1;
194             }
195              
196             # Set options for argument parsing
197 57 100       276 if (defined $options) {
198 2 100       11 if (exists $options->{-minimal_keys}) {
199 1         3 $minimal_keys = 1;
200             }
201 2 100       11 if (exists $options->{-vars}) {
202 1         5 $vars_prefix = $options->{-vars};
203             }
204             }
205              
206 57         211 %ARGV = ();
207              
208             # Handle standard args...
209 57 50   629   1054 if ( first { $_ eq '--man' } @$args ) {
  629 50       1384  
    50          
    50          
    50          
210 0         0 _print_pod( __PACKAGE__->man(), 'paged' );
211 0         0 exit;
212 629     629   1030 } elsif ( first { $_ eq '--usage' } @$args ) {
213 0         0 print __PACKAGE__->usage();
214 0         0 exit;
215 629     629   1023 } elsif ( first { $_ eq '--help' } @$args ) {
216 0         0 _print_pod( __PACKAGE__->help(), 'paged' );
217 0         0 exit;
218 629     629   989 } elsif ( first { $_ eq '--version' } @$args ) {
219 0         0 print __PACKAGE__->version();
220 0         0 exit;
221 629     629   807 } elsif ( first { $_ eq '--podfile' } @$args ) {
222             # Option meant for authors
223 0         0 my $podfile = podfile( );
224 0         0 print "Wrote POD manual in file $podfile\n";
225 0         0 exit;
226             }
227              
228             # Subroutine to report problems during parsing...
229             *_bad_arglist = sub {
230 16     16   46 my (@msg) = @_;
231 16         132 my $msg = join q{}, @msg;
232 16         85 $msg = _rectify_arg($msg);
233 16         113 $msg =~ s/\n?\z/\n/xms;
234 16         217 warn "$msg\nTry this for usage help: $SCRIPT_NAME --help\n".
235             "Or this for full manual: $SCRIPT_NAME --man\n\n";
236 16         109 exit 2; # Traditional "bad arg list" value
237 57         1268 };
238              
239             # Run matcher...
240 57         189 my $argv = join( q{ }, map { $_ = _escape_arg($_) } @$args );
  629         4042  
241 57         639 my $all_args_ref = { %options, %requireds };
242 57 100       308 if ( my $error = _doesnt_match( $matcher, $argv, $all_args_ref ) ) {
243 7         35 _bad_arglist($error);
244             }
245              
246             # Check that all requireds have been found...
247 50         123 my @missing;
248 50         320 while ( my ($req) = each %requireds ) {
249 101 100       578 push @missing, "\t$req\n" if !exists $ARGV{$req};
250             }
251             _bad_arglist(
252 50 50       218 'Missing required argument',
    100          
253             ( @missing == 1 ? q{} : q{s} ),
254             ":\n", @missing
255             ) if @missing;
256              
257             # Back-translate \0-quoted spaces and \1-quoted tabs...
258 49         238 _rectify_all_args();
259              
260             # Check exclusive variables, variable constraints and fill in defaults...
261 49         1628 _verify_args($all_args_ref);
262              
263             # Clean up @$args since everything must have been parsed
264 41         293 @$args = ();
265              
266             # Clean up %ARGV
267 41         169 for my $arg_name ( keys %ARGV ) {
268              
269             # Flatten non-repeatables...
270 260         1700 my $vals = delete $ARGV{$arg_name};
271 260         669 my $repeatable = $all_args_ref->{$arg_name}{is_repeatable};
272 260 100       585 if ($repeatable) {
273 4         5 pop @{$vals};
  4         7  
274             }
275              
276 260         309 for my $val ( @{$vals} ) {
  260         574  
277 261         294 my $var_count = keys %{$val};
  261         555  
278 215         492 $val = $var_count == 0
279             ? 1 # Boolean -> true
280             : $var_count == 1
281 261 100       707 ? ( values %{$val} )[0] # Single var -> var's val
    50          
282             : $val # Otherwise keep hash
283             ;
284 261         792 my $false_vals = $all_args_ref->{$arg_name}{false_vals};
285 261         304 my %vars_opt_vals;
286              
287 261         649 for my $arg_flag ( _get_variants($arg_name) ) {
288 481         637 my $variant_val = $val;
289 481 100 100     1468 if ( $false_vals && $arg_flag =~ m{\A $false_vals \z}xms ) {
290 14 100       43 $variant_val = $variant_val ? 0 : 1;
291             }
292              
293 481 100       850 if ($repeatable) {
294 25         25 push @{ $ARGV{$arg_flag} }, $variant_val;
  25         56  
295             } else {
296 456         988 $ARGV{$arg_flag} = $variant_val;
297             }
298 481 100       1339 $vars_opt_vals{$arg_flag} = $ARGV{$arg_flag} if $vars_prefix;
299             }
300              
301 261 100       1189 if ($vars_prefix) {
302 28         60 _minimize_entries_of( \%vars_opt_vals );
303 28         76 my $maximal = _longestname( keys %vars_opt_vals );
304 28         74 _export_var( $vars_prefix, $maximal, $vars_opt_vals{$maximal} );
305 28         152 delete $longnames{$maximal};
306             }
307             }
308             }
309              
310 41 100       309 if ($vars_prefix) {
311              
312             # Export any unspecified options to keep use strict happy
313 3         19 while ( my ($opt_name, $arg_name) = each %longnames ) {
314 17         33 my $arg_info = $all_args_ref->{$arg_name};
315 17         22 my $val;
316 17 100 100     102 if ( $arg_info->{is_repeatable} or $arg_name =~ />\.\.\./ ) {
317             # Empty arrayref for repeatable options
318 3         7 $val = [];
319             } else {
320 14 100       19 if (keys %{ $arg_info->{var} } > 1) {
  14         63  
321             # Empty hashref for non-repeatable options with multiple placeholders
322 1         4 $val = {};
323             }
324             }
325 17         38 _export_var( $vars_prefix, $opt_name, $val );
326             }
327             }
328              
329              
330 41 100       154 if ($minimal_keys) {
331 6         30 _minimize_entries_of( \%ARGV );
332             }
333              
334 41         241 return 1;
335             }
336              
337              
338             sub podfile {
339             # Write the given POD doc into a .pod file, overwriting any existing .pod file
340 1 50   1 1 1348 return if not -e $0;
341 1         44 my ($name_re, $path, $suffix) = fileparse($0, qr/\.[^.]*/);
342 1         13 my $pod_file = catfile( $path, $name_re.'.pod' );
343 1 50       6533 open my $out_fh, '>', $pod_file or croak "Could not write file $pod_file because $!";
344 1         22 print $out_fh $pod_file_msg."\n\n".__PACKAGE__->man();
345 1         91 close $out_fh;
346 1         13 return $pod_file;
347             }
348              
349              
350             sub man {
351 6     6 1 39026 return $man;
352             }
353              
354              
355             sub usage {
356 1     1 1 2047 return $usage;
357             }
358              
359              
360             sub help {
361 2     2 1 7981 return $help;
362             }
363              
364              
365             sub version {
366 1     1 1 2400 return $version;
367             }
368              
369              
370             # # # # # # # # Utility subs # # # # # # # #
371              
372             # Recursively remove decorations on %ARGV keys
373              
374             sub AUTOLOAD {
375 9     9   17 our $AUTOLOAD;
376 9         199 $AUTOLOAD =~ s{.*::}{main::}xms;
377 65     65   1190 no strict 'refs';
  65         211  
  65         1506772  
378 9         94 goto &$AUTOLOAD;
379             }
380              
381              
382             sub _parse_pod {
383             # Set up parsing rules...
384 64     64   6117 my $space_re = qr{ [^\S\n]* }xms;
385 64         325 my $head_start_re = qr{ ^=head1 }xms;
386 64         2267 my $head_end_re = qr{ (?= $head_start_re | \z) }xms;
387 64         489 my $pod_cmd_re = qr{ = [^\W\d]\w+ [^\n]* (?= \n\n )}xms;
388 64         2468 my $pod_cut_re = qr{ (?! \n\n ) = cut $space_re (?= \n\n )}xms;
389              
390 64         8232 my $name_re = qr{ $space_re NAME $space_re \n }xms;
391 64         9187 my $vers_re = qr{ $space_re VERSION $space_re \n }xms;
392 64         9447 my $usage_re = qr{ $space_re USAGE $space_re \n }xms;
393              
394 64         1118 my $std_re = qr{ STANDARD | STD | PROGRAM | SCRIPT | CLI | COMMAND(?:-|\s)?LINE }xms;
395 64         6803 my $arg_re = qr{ $space_re (?:PARAM(?:ETER)?|ARG(?:UMENT)?)S? }xms;
396              
397 64         23650 my $options_re = qr{ $space_re $std_re? $space_re OPTION(?:AL|S)? $arg_re? $space_re \n }xms;
398 64         18874 my $required_re = qr{ $space_re $std_re? $space_re (?:REQUIRED|MANDATORY) $arg_re? $space_re \n }xms;
399              
400 64         2095 my $euclid_arg = qr{ ^=item \s* ([^\n]*?) \s* \n\s*\n
401             (
402             .*?
403             (?:
404             ^=for \s* (?i: Euclid) .*? \n\s*\n
405             | (?= ^=[^\W\d]\w* | \z)
406             )
407             )
408             }xms;
409              
410             # Clean up line delimiters
411 64         3537 $man =~ s{ [\n\r] }{\n}gx;
412              
413             # Clean up significant entities...
414 64         319 $man =~ s{ E<lt> }{<}gxms;
415 64         254 $man =~ s{ E<gt> }{>}gxms;
416              
417             # Put program name in man
418 64 100       2496 $SCRIPT_NAME = (-e $0) ? (splitpath $0)[-1] : 'one-liner';
419 64 100       5181 $man =~ s{ ($head_start_re $name_re \s*) .*? (- .*)? $head_end_re }
  52         795  
420             {$1.$SCRIPT_NAME.($2 ? " $2" : "\n\n")}xems;
421              
422             # Put version number in man
423 64         3890 ($SCRIPT_VERSION) =
424             $man =~ m/$head_start_re $vers_re .*? (\d+(?:[._]\d+)+) .*? $head_end_re /xms;
425 64 100       711 if ( !defined $SCRIPT_VERSION ) {
426 14         32 $SCRIPT_VERSION = $main::VERSION;
427             }
428 64 100       288 if ( !defined $SCRIPT_VERSION ) {
429 14 100       3302 $SCRIPT_VERSION = (-e $0) ? localtime((stat $0)[9]) : 'one-liner';
430             }
431 64         4268 $man =~ s{ ($head_start_re $vers_re \s*) .*? (\s*) $head_end_re }
432             {$1This document refers to $SCRIPT_NAME version $SCRIPT_VERSION $2}xms;
433              
434             # Extra info from PODs
435 64         227 my ($options, $opt_name, $required, $req_name, $licence);
436 64         10436 while ($man =~ m/$head_start_re ($required_re) (.*?) $head_end_re /gxms) {
437             # Required arguments
438 51         344 my ( $more_req_name, $more_required ) = ($1, $2);
439 51 50       261 $req_name = $more_req_name if not defined $req_name;
440 51   50     1315 $required = ( $more_required || q{} ) . ( $required || q{} );
      50        
441             }
442 64         11028 while ($man =~ m/$head_start_re ($options_re) (.*?) $head_end_re /gxms) {
443             # Optional arguments
444 55         344 my ( $more_opt_name, $more_options ) = ($1, $2);
445 55 50       268 $opt_name = $more_opt_name if not defined $opt_name;
446 55   50     937 $options = ( $more_options || q{} ) . ( $options || q{} );
      50        
447             }
448 64         12529 while ($man =~ m/$head_start_re [^\n]+ (?i: licen[sc]e | copyright ) .*? \n \s* (.*?) \s* $head_end_re /gxms) {
449             # License information
450 47         210 my ($more_licence) = ($1, $2);
451 47   50     719 $licence = ( $more_licence || q{} ) . ( $licence || q{} );
      50        
452             }
453              
454             # Clean up interface titles...
455 64         226 for my $name_re ( $opt_name, $req_name ) {
456 128 100       427 next if !defined $name_re;
457 106         910 $name_re =~ s{\A \s+ | \s+ \z}{}gxms;
458             }
459              
460             # Extract the actual interface and store each arg entry into a hash of specifications...
461 64         182 my $seq = 0;
462 64         266 my $seen = {};
463 64   100     14782 while ( ( $required || q{} ) =~ m{ $euclid_arg }gxms ) {
464 120         819 $seen = _register_specs( $1, $2, $seq, \%requireds, \%longnames, $seen );
465 120         1816 $seq++;
466             }
467 64   100     7122 while ( ( $options || q{} ) =~ m{ $euclid_arg }gxms ) {
468 418         1124 $seen = _register_specs( $1, $2, $seq, \%options, \%longnames, $seen );
469 417         12298 $seq++;
470             }
471 63         173 undef $seen;
472 63         402 _minimize_entries_of( \%longnames );
473              
474             # Extract Euclid information...
475 63         495 my $all_specs = {%requireds, %options};
476 63         318 _process_euclid_specs( $all_specs );
477              
478             # Insert default values (if any) in the program's documentation
479 52         268 $required = _insert_default_values(\%requireds);
480 51         200 $options = _insert_default_values(\%options );
481              
482             # One-line representation of interface...
483 140         380 my $arg_summary = join ' ', (sort
484 51         220 { $requireds{$a}{'seq'} <=> $requireds{$b}{'seq'} }
485             (keys %requireds));
486              
487 51         603 1 while $arg_summary =~ s/\[ [^][]* \]//gxms;
488              
489 51 100       260 if ($opt_name) {
490 42 100       194 $arg_summary .= ' ' if $arg_summary;
491 42         170 $arg_summary .= lc "[$opt_name]";
492             }
493 51         338 $arg_summary =~ s/\s+/ /gxms;
494              
495             # Manual message
496 51         10148 $man =~ s{ ($head_start_re $usage_re \s*) .*? (\s*) $head_end_re } {$1$SCRIPT_NAME $arg_summary$2}xms;
497 51         17683 $man =~ s{ ($head_start_re $required_re \s*) .*? (\s*) $head_end_re } {$1$required$2}xms;
498 51         13434 $man =~ s{ ($head_start_re $options_re \s*) .*? (\s*) $head_end_re } {$1$options$2}xms;
499              
500             # Usage message
501 51         289 $usage = " $SCRIPT_NAME $arg_summary\n";
502 51         176 $usage .= " $SCRIPT_NAME --help\n";
503 51         195 $usage .= " $SCRIPT_NAME --man\n";
504 51         199 $usage .= " $SCRIPT_NAME --usage\n";
505 51         205 $usage .= " $SCRIPT_NAME --version\n";
506              
507             # Help message
508 51         280 $help = "=head1 \L\uUsage:\E\n\n$usage\n";
509 51 100 100     722 $help .= "=head1 \L\u$req_name:\E\n\n$required\n\n"
510             if ( $req_name || q{} ) =~ /\S/;
511 51 100 100     732 $help .= "=head1 \L\u$opt_name:\E\n\n$options\n\n"
512             if ( $opt_name || q{} ) =~ /\S/;
513              
514 51         239 $usage = "Usage:\n".$usage;
515              
516             # Version message
517 51         241 $version = "This is $SCRIPT_NAME version $SCRIPT_VERSION\n";
518 51 100       521 $version .= "\n$licence\n" if $licence;
519              
520             # Convert arg specifications to regexes...
521 51         334 _convert_to_regex( $all_specs );
522              
523             # Build matcher...
524 51         262 my @arg_list = ( values(%requireds), values(%options) );
525 435         1160 $matcher = join '|', map { $_->{matcher} }
  1009         1577  
526 435         1398 sort( { $b->{name} cmp $a->{name} } grep { $_->{name} =~ /^[^<]/ } @arg_list ),
  1         4  
527 51         202 sort( { $a->{seq} <=> $b->{seq} } grep { $_->{name} =~ /^[<]/ } @arg_list );
  435         965  
528 51         214 $matcher .= '|(?> (.+)) (?{ push @errors, $^N }) (?!)';
529 51         360 $matcher = '(?:' . $matcher . ')';
530              
531 51         1316 return 1;
532             }
533              
534              
535             sub _register_specs {
536 538     538   1721 my ($name_re, $spec, $seq, $storage, $longnames, $seen) = @_;
537 538         1857 my @variants = _get_variants($name_re);
538 538         3408 $storage->{$name_re} = {
539             seq => $seq,
540             src => $spec,
541             name => $name_re,
542             variants => \@variants,
543             };
544 538 100       1310 if ($minimal_keys) {
545 41         77 my $minimal = _minimize_name($name_re);
546 41 100       301 croak "Internal error: minimalist mode caused arguments ".
547             "'$name_re' and '".$seen->{$minimal}."' to clash"
548             if $seen->{$minimal};
549 40         129 $seen->{$minimal} = $name_re;
550             }
551 537         1400 $longnames->{ _longestname(@variants) } = $name_re;
552 537         1720 return $seen;
553             }
554              
555              
556             sub _process_euclid_specs {
557 63     63   204 my ($args) = @_;
558 63         351 my %all_var_list;
559             my %excluded_by_def;
560              
561             ARG:
562 63         487 while ( (undef, my $arg) = each %$args ) {
563              
564             # Validate and record variable names seen here...
565 483         1919 my $var_list = _validate_name( $arg->{name} );
566 481         3568 while (my ($var_name, undef) = each %$var_list) {
567 367         1447 $all_var_list{$var_name} = undef;
568             }
569              
570             # Process arguments with a Euclid specification further
571 481 100       4062 $arg->{src} =~ s{^ =for \s+ Euclid\b [^\n]* \s* (.*) \z}{}ixms
572             or next ARG;
573 235         615 my $info = $1;
574              
575 235         747 $arg->{is_repeatable} = $info =~ s{^ \s* repeatable \s*? $}{}xms;
576              
577 235         322 my @false_vals;
578 235         3001 while ( $info =~ s{^ \s* false \s*[:=] \s* ([^\n]*)}{}xms ) {
579 10         23 my $regex = $1;
580 10         128 1 while $regex =~ s/ \[ ([^]]*) \] /(?:$1)?/gxms;
581 10         23 $regex =~ s/ (\s+) /$1.'[\\s\\0\\1]*'/egxms;
  0         0  
582 10         42 push @false_vals, $regex;
583             }
584 235 100       622 if (@false_vals) {
585 8         68 $arg->{false_vals} = '(?:' . join( '|', @false_vals ) . ')';
586             }
587              
588 235         1515 while (
589             $info =~ m{\G \s* (([^.]+)\.([^:=\s]+) \s*[:=]\s* ([^\n]*)) }gcxms )
590             {
591 398         1552 my ( $spec, $var, $field, $val ) = ( $1, $2, $3, $4 );
592              
593             # Check for misplaced fields...
594 398 100       14610 if ( $arg->{name} !~ m{\Q<$var>}xms ) {
595 1         9 _fail( "Invalid constraint: $spec\n(No <$var> placeholder in ".
596             "argument: $arg->{name})" );
597             }
598              
599             # Decode...
600 397 100 100     4978 if ( $field eq 'type.error' ) {
    100          
    100          
    100          
    100          
601 2         15 $arg->{var}{$var}{type_error} = $val;
602             } elsif ( $field eq 'type' ) {
603 234         594 $val = _qualify_variables_fully( $val );
604 234         1378 my ( $matchtype, $comma, $constraint ) =
605             $val =~ m{(/(?:\.|.)+/ | [^,\s]+)\s*(?:(,))?\s*(.*)}xms;
606 234         1028 $arg->{var}{$var}{type} = $matchtype;
607 234 100 66     1663 if ( $comma && length $constraint ) {
    100          
608 18         414 ( $arg->{var}{$var}{constraint_desc} = $constraint ) =~
609             s/\s*\b\Q$var\E\b\s*//g;
610 18         379 $constraint =~ s/\b\Q$var\E\b/\$_[0]/g;
611 18 50       2134 $arg->{var}{$var}{constraint} = eval "sub{ $constraint }"
612             or _fail("Invalid .type constraint: $spec\n($@)");
613             } elsif ( length $constraint ) {
614 39         167 $arg->{var}{$var}{constraint_desc} = $constraint;
615 39 50       9294 $arg->{var}{$var}{constraint} =
616             eval "sub{ \$_[0] $constraint }"
617             or _fail("Invalid .type constraint: $spec\n($@)");
618             } else {
619 177         632 $arg->{var}{$var}{constraint_desc} = $matchtype;
620             $arg->{var}{$var}{constraint} =
621             $matchtype =~ m{\A\s*/.*/\s*\z}xms
622 4     4   21 ? sub { 1 }
623 177 100       2345 : $std_constraint_for{$matchtype}
    100          
624             or _fail("Unknown .type constraint: $spec");
625             }
626              
627             } elsif ( ($field eq 'default') || ($field eq 'opt_default') ) {
628 153         338 $val = _qualify_variables_fully( $val );
629 153 100       952428 eval "\$val = $val; 1"
630             or _fail("Invalid .$field value: $spec\n($@)");
631 152         720 $arg->{var}{$var}{$field} = $val;
632 152         349 my $has_field = 'has_'.$field;
633 152 100       590 $arg->{$has_field} = exists $arg->{$has_field} ?
634             $arg->{$has_field}++ :
635             1;
636              
637 152 100       861 if ($field eq 'opt_default') {
638             # Check that placeholders with optional defaults have a flagged argument
639 8 100       154 if ( $arg->{name} =~ m{^<}xms ) {
640 1         9 _fail( "Invalid .$field constraint: $spec\nParameter ".
641             "$arg->{name} must have a flag" );
642             }
643             # Check that placeholders with optional defaults is optional
644 7 100       207 if ( $arg->{name} !~ m{\Q[<$var>]}xms ) {
645 1         9 _fail( "Invalid .$field constraint: $spec\nPlaceholder".
646             " <$var> must be optional, i.e. [<$var>], to have ".
647             "an optional default in argument: $arg->{name}" );
648             }
649             }
650              
651             } elsif ( $field eq 'excludes.error' ) {
652 1         6 $arg->{var}{$var}{excludes_error} = $val;
653             } elsif ( $field eq 'excludes' ) {
654 6         39 $arg->{var}{$var}{excludes} = [ split '\s*,\s*', $val ];
655 6         16 for my $excl_var (@{$arg->{var}{$var}{excludes}}) {
  6         23  
656 8 100       48 if ($var eq $excl_var) {
657 1         5 _fail( "Invalid .excludes value for variable <$var>: ".
658             "<$excl_var> cannot exclude itself." );
659             }
660             }
661             } else {
662 1         6 _fail("Unknown specification: $spec");
663             }
664             }
665             # Record variables excluded by another that has a default
666 228         353 while (my ($var_name, $var_data) = each %{$arg->{var}}) {
  481         1860  
667 253         338 for my $excl_var (@{$arg->{var}{$var_name}{excludes}}) {
  253         1077  
668 7 100       51 $excluded_by_def{$excl_var}{default}{$var_name} = 1 if $arg->{has_default};
669 7 50       33 $excluded_by_def{$excl_var}{opt_default}{$var_name} = 1 if $arg->{has_opt_default};
670             }
671             }
672 228 100       2071 if ( $info =~ m{\G \s* ([^\s\0\1] [^\n]*) }gcxms ) {
673 1         8 _fail("Unknown specification: $1");
674             }
675             }
676              
677             # Validate and complete .excludes specs
678              
679 53         339 while ( (undef, my $arg) = each %$args ) {
680 448         685 while ( my ($var, $var_specs) = each %{$arg->{var}} ) {
  690         3341  
681             # Check for invalid placeholder name in .excludes specifications
682 243         296 for my $excl_var (@{$var_specs->{excludes}}) {
  243         664  
683 7 100       23 if (not exists $all_var_list{$excl_var}) {
684 1         6 _fail( "Invalid .excludes value for variable <$var>: ".
685             "<$excl_var> does not exist\n" );
686             }
687             }
688             # Remove default for placeholders excluded by others that have a default
689 242         395 for my $type ( 'default', 'opt_default' ) {
690 484 100 100     2365 if ( (exists $arg->{var}->{$var}->{$type}) && (exists $excluded_by_def{$var}{$type}) ) {
691 3         7 delete $arg->{var}->{$var}->{$type};
692 3         9 $arg->{"has_$type"}--;
693 3 100       10 if ($arg->{"has_$type"} == 0) {
694 2         5 delete $arg->{"has_$type"};
695             }
696             }
697             }
698             }
699             }
700              
701 52         242 return 1;
702             }
703              
704              
705             sub _qualify_variables_fully {
706             # Restore fully-qualified name to variables:
707             # $x becomes $main::x
708             # $::x becomes $main::x
709             # $Package::x stays as $Package::x
710             # /^asdf$/ stays as /^asdf$/
711             # '$10' stays as '$10'
712             # Note: perlvar indicates that ' can also be used instead of ::
713 387     387   646 my ($val) = @_;
714 387 100       1200 if ($val =~ m/[\$\@\%]/) { # Avoid expensive Text::Balanced operations when there are no variables
715 9         12 my $new_val;
716 9     294   69 for my $s (extract_multiple($val,[{Quoted=>sub{extract_delimited($_[0])}}],undef,0)) {
  294         32063  
717 10 100       620 if (not ref $s) {
718             # A non-quoted section... may contain variables to fix
719 9         14 for my $var_name ( @{_get_variable_names($s)} ) {
  9         20  
720             # Skip fully qualified names, such as '$Package::x'
721 11 100       38 next if $var_name =~ m/main(?:'|::)/;
722             # Remove sigils from beginning of variable name: $ @ % {
723 10         35 $var_name =~ s/^[\$\@\%\{]+//;
724             # Substitute non-fully qualified vars, e.g. '$x' or '$::x', by '$main::x'
725 10         41 my $new_name = Symbol::qualify($var_name, 'main');
726 10 100       154 next if $new_name eq $var_name;
727 9         20 $var_name = quotemeta( $var_name );
728 9         120 $s =~ s/$var_name/$new_name/;
729             }
730 9         45 $new_val .= $s;
731             } else {
732             # A quoted section, to keep as-is
733 1         3 $new_val .= $$s;
734             }
735             }
736 9         84 return $new_val;
737             } else {
738 378         1026 return $val;
739             }
740             }
741              
742              
743             sub _get_variable_names {
744             # Get an arrayref of the variables names found in the provided string.
745             # This function is a hack, needed only because of Text::Balanced ticket #78855:
746             # https://rt.cpan.org/Public/Bug/Display.html?id=78855
747 9     9   17 my ($str) = @_;
748 9         15 my $vars = [];
749 9     172   60 for my $var (extract_multiple($str,[sub{extract_variable($_[0],'')}],undef,1)) {
  172         1782123  
750             # Name must start with underscore or a letter, e.g. $t $$h{a} ${$h}{a} $h->{a} @_
751             # Skip special or invalid names, e.g. $/ $1
752 13         1291 my $tmp = $var;
753 13         60 $tmp =~ s/(?:{|})//g;
754 13 100       55 next if not $tmp =~ m/^[\$\@\%]+[_a-z]/i;
755 11         29 push @$vars, $var;
756             }
757 9         87 return $vars;
758             }
759              
760              
761             sub _minimize_name {
762 701     701   944 my ($name_re) = @_;
763 701         1156 $name_re =~ s{[][]}{}gxms; # remove all square brackets
764 701         2781 $name_re =~ s{\A \W+ ([\w-]*) .* \z}{$1}gxms;
765 701         1101 $name_re =~ s{-}{_}gxms;
766 701         1405 return $name_re;
767             }
768              
769              
770             sub _minimize_entries_of {
771 97     97   213 my ($arg_ref) = @_;
772 97 50       1153 return if ref $arg_ref ne 'HASH';
773              
774 97         444 for my $old_key (keys %$arg_ref) {
775 660         1549 my $new_key = _minimize_name($old_key);
776 660         4541 $arg_ref->{$new_key} = delete $arg_ref->{$old_key};
777             }
778              
779 97         256 return 1;
780             }
781              
782              
783             # Do match, recursively trying to expand cuddles...
784             sub _doesnt_match {
785 62     62   227 my ( $matcher, $argv, $arg_specs_ref ) = @_;
786              
787 62         132 our @errors; # 'our' instead of 'my' because it is needed for the re pragma
788 62         193 local @errors = ();
789 62         196 %ARGV = ();
790              
791             # Match arguments, populate %ARGV and @errors
792             # Note that the matcher needs the pragma: use re 'eval';
793 62         2209687 $argv =~ m{\A (?: \s* $matcher )* \s* \z}xms;
794              
795             # Report errors in passed arguments
796 62         370 for my $error (@errors) {
797 12 100       73 if ( $error =~ m/\A ((\W) (\w) (\w+))/xms ) {
798 5         40 my ( $bundle, $marker, $firstchar, $chars ) = ( $1, $2, $3, $4 );
799 5         85 $argv =~ s{\Q$bundle\E}{$marker$firstchar $marker$chars}xms;
800 5 100       47 return if !_doesnt_match( $matcher, $argv, $arg_specs_ref );
801             }
802             ARG:
803 10         23 for my $arg_spec_ref ( values %{$arg_specs_ref} ) {
  10         46  
804 34         49 our $bad_type;
805 34         45 local $bad_type;
806             next ARG
807 34 100 66     5016 if $error !~ m/\A [\s\0\1]* ($arg_spec_ref->{generic_matcher})/xms
808             || !$bad_type;
809            
810 4         59 my $msg = _type_error( $bad_type->{arg}, $bad_type->{var},
811             $bad_type->{val}, $bad_type->{type}, $bad_type->{type_error} );
812 4         317 return $msg;
813             }
814 6         63 return "Unknown argument: $error";
815             }
816              
817 50         555 return 0; # No error
818             }
819              
820              
821             sub _escape_arg {
822 629     629   2326 my $arg = shift;
823 629         1047 my ($num_replaced) = ($arg =~ tr/ \t/\0\1/);
824 629         1786 return $arg;
825             }
826              
827              
828             sub _rectify_arg {
829 428     428   586 my $arg = shift;
830 428         736 my ($num_replaced) = ($arg =~ tr/\0\1/ \t/);
831 428         2130 return $arg;
832             }
833              
834              
835             sub _rectify_all_args {
836 49     49   318 while ( my (undef, $arg_list) = each %ARGV ) {
837 275         336 for my $arg ( @{$arg_list} ) {
  275         587  
838 286 50       895 if ( ref $arg eq 'HASH' ) {
839 286         315 for my $var ( values %{$arg} ) {
  286         696  
840 312 100       612 if ( ref $var eq 'ARRAY' ) {
841 35         37 $var = [ map { _rectify_arg($_) } @{$var} ];
  135         226  
  35         126  
842             } else {
843 277         577 $var = _rectify_arg($var);
844             }
845             }
846             } else {
847 0 0       0 if ( ref $arg eq 'ARRAY' ) {
848 0         0 $arg = [ map { _rectify_arg($_) } @{$arg} ];
  0         0  
  0         0  
849             } else {
850 0         0 $arg = _rectify_arg($arg);
851             }
852             }
853             }
854             }
855 49         105 return 1;
856             }
857              
858              
859             sub _verify_args {
860 49     49   109 my ($arg_specs_ref) = @_;
861             # Check exclusive variables, variable constraints and fill in defaults...
862             # Handle mutually exclusive arguments
863 49         109 my %seen_vars;
864 49         255 while ( my ($arg_name, $arg_elems) = each %ARGV ) {
865 275         401 for my $elem (@{$arg_elems}) {
  275         448  
866 286         324 while ( my ($var_name) = each (%{$elem}) ) {
  598         2454  
867 312 100       989 $seen_vars{$var_name} = $arg_name if $var_name;
868             }
869             }
870             }
871              
872 49         129 while ( my ($arg_name, $arg) = each %{$arg_specs_ref} ) {
  507         1525  
873 461         1015 while ( my ($var_name, $var) = each %{$arg->{var}} ) {
  814         2695  
874             # Enforce placeholders that cannot be specified with others
875 356         421 for my $excluded_var ( @{$var->{excludes}} ) {
  356         975  
876 13 100 66     55 if (exists $seen_vars{$var_name} &&
877             exists $seen_vars{$excluded_var}) {
878 3         6 my $excl_arg = $seen_vars{$excluded_var};
879 3         4 my $msg;
880 3 100       11 if (exists $var->{excludes_error}) {
881 1         3 $msg = $var->{excludes_error};
882             } else {
883 2         12 $msg =
884             qq{Invalid "$excl_arg" argument.\n<$excluded_var> }.
885             qq{cannot be specified with <$var_name> because }.
886             qq{argument "$arg_name" excludes <$excluded_var>};
887             }
888 3         10 _bad_arglist($msg);
889             }
890             }
891             }
892             }
893              
894             # Enforce constraints and fill in defaults...
895             ARG:
896 46         131 while (my ($arg_name, $arg_specs) = each %{$arg_specs_ref} ) {
  433         1624  
897              
898             # Skip non-existent/non-defaulting/non-optional-defaulting arguments
899             next ARG
900 392 100 100     1920 if !exists $ARGV{$arg_name}
      66        
901             && !( $arg_specs->{has_default}
902             || $arg_specs->{has_opt_default} );
903              
904             # Ensure all vars exist within arg...
905 275         1847 my @vars = keys %{$arg_specs->{placeholders}};
  275         1168  
906 275         405 for my $index ( 0 .. $#{ $ARGV{$arg_name} } ) {
  275         1973  
907 251         546 my $entry = $ARGV{$arg_name}[$index];
908 251         1660 @{$entry}{@vars} = @{$entry}{@vars};
  251         635  
  251         1878  
909              
910             # Get arg specs...
911             VAR:
912 251         563 for my $var (@vars) {
913              
914 258         571 my $arg_vars = $arg_specs->{var}->{$var};
915              
916             # Check constraints on vars...
917 258 50       655 if ( exists $ARGV{$arg_name} ) {
918              
919 258 100 66     2278 if ( ref $entry eq 'HASH' && defined $entry->{$var} ) {
    50 33        
920             # Named vars...
921 229 100       2244 for my $val (
  35         70  
922             ref $entry->{$var} eq 'ARRAY'
923             ? @{ $entry->{$var} }
924             : $entry->{$var}
925             )
926             {
927 329 100 100     34661 if ( $arg_vars->{constraint} &&
928             !$arg_vars->{constraint}->($val) ) {
929 5         41 _bad_arglist( _type_error($arg_name, $var, $val,
930             $arg_vars->{constraint_desc},
931             $arg_vars->{type_error}) );
932             }
933             }
934 224         922 next VAR;
935             } elsif ( ref $entry ne 'HASH' && defined $entry ) {
936             # Unnamed vars...
937 0 0       0 for my $val (
  0         0  
938             ref $entry eq 'ARRAY'
939             ? @{$entry}
940             : $entry
941             )
942             {
943 0 0 0     0 if ( $arg_vars->{constraint} &&
944             !$arg_vars->{constraint}->($val) ) {
945 0         0 _bad_arglist( _type_error( $arg_name, $var, $val,
946             $arg_vars->{constraint_desc},
947             $arg_vars->{type_error}) );
948             }
949 0 0       0 $entry->{$var} = ''
950             unless defined( $ARGV{$arg_name} );
951             }
952 0         0 next VAR;
953             }
954             }
955              
956             # Assign placeholder defaults (if necessary)...
957             next ARG
958 29 100 66     211 if !exists $arg_vars->{default}
959             && !exists $arg_vars->{opt_default};
960              
961 17 100       276 $entry->{$var} = exists $arg_vars->{opt_default} ?
962             $arg_vars->{opt_default} :
963             $arg_vars->{default};
964             }
965             }
966              
967             # Handle defaults for missing args...
968 258 100       698 if ( !@{ $ARGV{$arg_name} } ) {
  258         1157  
969 35         68 for my $var (@vars) {
970             # Assign defaults (if necessary)...
971 37         92 my $arg_vars = $arg_specs->{var}->{$var};
972             next ARG
973 37 100       234 if !exists $arg_vars->{default}; # no default specified
974              
975             # Omit default if it conflicts with a specified parameter
976 32         57 for my $excl_var ( @{$arg_specs->{var}->{$var}->{excludes}} ) {
  32         102  
977 5 100       12 if (exists $seen_vars{$excl_var}) {
978 3         9 next ARG;
979             }
980             }
981              
982 29         168 $ARGV{$arg_name}[0]{$var} = $arg_vars->{default};
983             }
984             }
985             }
986 41         162 return 1;
987             }
988              
989              
990             sub _type_error {
991 9     9   36 my ($arg_name, $var_name, $var_val, $var_constraint, $var_error) = @_;
992 9         36 my $msg = qq{Invalid "$arg_name" argument.\n};
993 9         42 $var_name =~ s{\W+}{}gxms;
994 9 100       33 if ( $var_error ) {
995 3         5 $msg = $var_error;
996 3         78 $msg =~ s{(?<!<)\b$var_name\b|\b$var_name\b(?!>)}{$var_val}gxms;
997             } else {
998 6         32 $msg = qq{<$var_name> must be $var_constraint but the supplied value }.
999             qq{("$var_val") is not.};
1000             }
1001 9         132 return $msg;
1002             }
1003              
1004              
1005             sub _convert_to_regex {
1006 51     51   171 my ($args_ref) = @_;
1007              
1008             # Regexp to capture the start of a new argument
1009 51         149 my $no_esc_ws = '(?!\0)'; # no escaped whitespaces
1010              
1011 51         132 my @arg_variants;
1012 51         2048 while ( my ($arg_name, $arg_specs) = each %{$args_ref} ) {
  486         1612  
1013 435         465 push @arg_variants, @{$arg_specs->{variants}};
  435         1657  
1014             }
1015              
1016 51         294 my $no_match = join('|',@arg_variants);
1017 51         250 $no_match = _escape_specials($no_match);
1018 51         219 $no_match = '(?!(?:'.$no_match.')'.$no_esc_ws.')';
1019              
1020 51         159 while ( my ($arg_name, $arg) = each %{$args_ref} ) {
  486         1694  
1021 435         657 my $regex = $arg_name;
1022              
1023             # Quotemeta specials...
1024 435         869 $regex = _escape_specials($regex);
1025 435         1023 $regex = "(?:$regex)";
1026              
1027             # Convert optionals...
1028 435         4438 1 while $regex =~ s/ \[ ([^]]*) \] /(?:$1)?/gxms;
1029 435         1190 $regex =~ s/ (\s+) /$1.'\s*'.$no_esc_ws/egxms;
  321         1193  
1030 435         749 my $generic = $regex;
1031              
1032             # Set the matcher
1033             $regex =~
1034             s{ < (.*?) >(\.\.\.|) }
1035 347         890 { my ($var_name, $var_rep) = ($1, $2);
1036 347         483 $var_name =~ s/(\s+)\[\\s\\0\\1]\*/$1/gxms;
1037 347   100     5774 my $type = $arg->{var}{$var_name}{type} || q{};
1038 347         1016 $arg->{placeholders}->{$var_name} = undef;
1039 347 100       11027 my $matcher =
    50          
1040             $type =~ m{\A\s*/.*/\s*\z}xms
1041             ? eval "qr$type"
1042             : $std_matcher_for{ $type }
1043             or _fail("Unknown type ($type) in specification: $arg_name");
1044 347 100       11570 $var_rep ?
1045             "(?:[\\s\\0\\1]*$no_match($matcher)(?{push \@{(\$ARGV{q{$arg_name}}||=[{}])->[-1]{q{$var_name}}}, \$^N}))+"
1046             :
1047             "(?:$no_match($matcher)(?{(\$ARGV{q{$arg_name}}||=[{}])->[-1]{q{$var_name}} = \$^N}))";
1048             }gexms
1049 435 100       2025 or do {
1050 167         481 $regex .= "(?{(\$ARGV{q{$arg_name}}||=[{}])->[-1]{q{}} = 1})";
1051             };
1052              
1053 435 100       2456 if ( $arg->{is_repeatable} ) {
1054 6         29 $arg->{matcher} = "$regex (?:(?<!\\w)|(?!\\w)) (?{push \@{\$ARGV{q{$arg_name}}}, {} })";
1055             } else {
1056 429 100       2600 $arg->{matcher} = "(??{exists\$ARGV{q{$arg_name}}?'(?!)':''}) "
1057             . (
1058             $arg->{false_vals}
1059             ? "(?:$arg->{false_vals} (?:(?<!\\w)|(?!\\w)) (?{\$ARGV{q{$arg_name}} ||= [{ q{} => 0 }] }) | $regex (?:(?<!\\w)|(?!\\w)) (?{\$ARGV{q{$arg_name}} ||= [{ q{} => 1}] }))"
1060             : "$regex (?:(?<!\\w)|(?!\\w)) (?{\$ARGV{q{$arg_name}} ||= [{}] })"
1061             );
1062             }
1063              
1064             # Set the generic matcher
1065 435         1507 $generic =~
1066             s{ < (.*?) > }
1067 347         4468 { my $var_name = $1;
1068 347         1821 $var_name =~ s/(\s+)\[\\s\\0\\1]\*/$1/gxms;
1069 347   100     1353 my $type = $arg->{var}{$var_name}{type} || q{};
1070 347   100     1815 my $type_error = $arg->{var}{$var_name}{type_error} || q{};
1071 347 100       1131 my $matcher = $type =~ m{\A\s*/.*/\s*\z}xms
1072             ? eval "qr$type"
1073             : $std_matcher_for{ $type };
1074 347         5552 "(?:($matcher|([^\\s\\0\\1]+)"
1075             . "(?{\$bad_type ||= "
1076             . "{arg=>q{$arg_name},type=>q{$type},type_error=>q{$type_error}, var=>q{<$var_name>},val=>\$^N};})))"
1077             }gexms;
1078 435         3324 $arg->{generic_matcher} = $generic;
1079             }
1080 51         191 return 1;
1081             }
1082              
1083              
1084             sub _escape_specials {
1085             # Escape quotemeta special characters
1086 486     486   796 my $arg = shift;
1087 486         5449 $arg =~ s{([@#\$^*()+{}?])}{\\$1}gxms;
1088 486         993 return $arg;
1089             }
1090              
1091              
1092             sub _print_pod {
1093 0     0   0 my ( $pod, $paged ) = @_;
1094              
1095 0 0       0 if ($paged) {
1096             # Page output
1097 0 0       0 eval { require IO::Pager::Page } or eval { require IO::Page };
  0         0  
  0         0  
1098             }
1099            
1100             # Convert POD to plaintext, wrapping the lines at 76 chars and print to STDOUT
1101 0 0       0 open my $parser_in, '<', \$pod or croak "Could not read from variable because $!";
1102 0         0 Pod::PlainText->new()->parse_from_filehandle($parser_in);
1103 0         0 close $parser_in;
1104              
1105 0         0 return 1;
1106             }
1107              
1108              
1109             sub _validate_name {
1110             # Check that the argument name only has pairs of < > brackets (ticket 34199)
1111             # Return the name of the variables that this argument specifies
1112 483     483   1234 my ($name) = @_;
1113 483 100       2131 if ($name =~ m/[<>]/) { # skip expensive Text::Balance functions if possible
1114 296         705 my %var_names;
1115 296         444 my $pos = 0;
1116 296     3365   2365 for my $s (extract_multiple($name,[sub{extract_bracketed($_[0],'<>')}],undef,0)) {
  3365         283624  
1117 819 100       1997040 next if not $s =~ m/[<>]/;
1118 382         2425 $s =~ s/^<(.*)>$/$1/;
1119 382 100       1194 if ( $s =~ m/[<>]/ ) {
1120 2         12 _fail( 'Invalid argument specification: '.$name );
1121             }
1122 380         487 $pos++;
1123 380 100       1811 $var_names{$s} = $pos if not exists $var_names{$s};
1124             }
1125 294         2109 return \%var_names;
1126             } else {
1127 187         551 return {};
1128             }
1129             }
1130              
1131              
1132             sub _get_variants {
1133 799     799   32372 my @arg_desc = shift =~ m{ [^[|]+ (?: $optional_re [^[|]* )* }gmxs;
1134              
1135 799         1867 for (@arg_desc) {
1136 824         5679 s{^ \s+ | \s+ $}{}gxms;
1137             }
1138              
1139             # Only consider first "word"...
1140 799 100       3342 return $1 if $arg_desc[0] =~ m/\A (< [^>]+ >)/xms;
1141              
1142 762         3971 $arg_desc[0] =~ s/\A ([^\s<]+) \s* (?: < .*)? \z/$1/xms;
1143              
1144             # Variants are all those with and without each optional component...
1145 762         1112 my %variants;
1146 762         2996 while (@arg_desc) {
1147 3054         4388 my $arg_desc_with = shift @arg_desc;
1148 3054         4538 my $arg_desc_without = $arg_desc_with;
1149              
1150 3054 100       11288 if ( $arg_desc_without =~ s/ \[ [^][]* \] //xms ) {
1151 1167         15047 push @arg_desc, $arg_desc_without;
1152             }
1153 3054 100       10070 if ( $arg_desc_with =~ m/ [[(] ([^][()]*) [])] /xms ) {
1154 1167         2003 my $option = $1;
1155 1167         2721 for my $alternative ( split /\|/, $option ) {
1156 1100         1420 my $arg_desc = $arg_desc_with;
1157 1100         3268 $arg_desc =~ s{[[(] [^][()]* [])]}{$alternative}xms;
1158 1100         3400 push @arg_desc, $arg_desc;
1159             }
1160             }
1161              
1162 3054         7656 $arg_desc_with =~ s/[][]//gxms;
1163 3054         8628 $arg_desc_with =~ s/\b[^-\w] .* \z//xms;
1164 3054         11553 $variants{$arg_desc_with} = 1;
1165             }
1166              
1167 762         3262 return keys %variants;
1168             }
1169              
1170              
1171             sub _longestname {
1172 565 50   565   1895 return ( sort { length $a <=> length $b || $a cmp $b } @_ )[-1];
  543         1854  
1173             }
1174              
1175              
1176             sub _export_var {
1177 45     45   276 my ( $prefix, $key, $value ) = @_;
1178 45         85 my $export_as = $prefix . $key;
1179 45         104 $export_as =~ s{\W}{_}gxms; # mainly for '-'
1180 45   50     227 my $callpkg = caller( $export_lvl + ($Exporter::ExportLevel || 0) );
1181 65     65   1008 no strict 'refs';
  65         570  
  65         30129  
1182 45 100       93 *{"$callpkg\::$export_as"} = ( ref $value ) ? $value : \$value;
  45         232  
1183 45         141 return 1;
1184             }
1185              
1186              
1187             # Utility sub to factor out hash key aliasing...
1188             sub _make_equivalent {
1189 130     130   758 my ( $hash_ref, %alias_hash ) = @_;
1190              
1191 130         740 while ( my ( $name_re, $aliases ) = each %alias_hash ) {
1192 910         1734 for my $alias (@$aliases) {
1193 2730         21636 $hash_ref->{$alias} = $hash_ref->{$name_re};
1194             }
1195             }
1196              
1197 130         402 return 1;
1198             }
1199              
1200              
1201             # Report problems in specification and die
1202             sub _fail {
1203 12     12   32 my (@msg) = @_;
1204 12         2997 croak "Getopt::Euclid: @msg";
1205             }
1206              
1207              
1208             sub _get_pod_names {
1209             # Parse the POD of the caller program and its modules.
1210 67     67   568 my @caller = caller(1);
1211              
1212             # Sanity check
1213 67 50       280 if ($has_run) {
1214 0         0 carp 'Getopt::Euclid loaded a second time';
1215 0         0 warn "Second attempt to parse command-line was ignored\n";
1216 0         0 return 0;
1217             }
1218              
1219             # Handle calls from .pm files
1220 67 100       419 if ( $caller[1] =~ m/[.]pm \z/xms ) {
1221 4         22 my @caller = caller(1); # at import()'s level
1222 4         13 push @pod_names, $caller[1];
1223             # Install this import() sub as module's import sub...
1224 65     65   433 no strict 'refs';
  65         160  
  65         112624  
1225 4         40 croak '.pm file cannot define an explicit import() when using Getopt::Euclid'
1226 4 50       8 if *{"$caller[0]::import"}{CODE};
1227 4         8 my $lambda; # Needed so the anon sub is generated at run-time
1228 4         20 *{"$caller[0]::import"}
1229 4     4   131 = bless sub { $lambda = 1; goto &Getopt::Euclid::import },
  4         57  
1230 4         48 'Getopt::Euclid::Importer';
1231              
1232 4         232 return 0;
1233             }
1234              
1235             # Add name of caller program
1236 63 100       2594 push @pod_names, $0 if (-e $0); # When calling perl -e '...', $0 is '-e', i.e. not a actual file
1237              
1238 63         334 return 1;
1239             }
1240              
1241              
1242             sub _insert_default_values {
1243 103     103   193 my ($args) = @_;
1244 103         193 my $pod_string = '';
1245             # Retrieve item names in sequential order
1246 103         736 for my $item_name ( sort { $args->{$a}->{'seq'} <=> $args->{$b}->{'seq'} } (keys %$args) ) {
  869         1645  
1247 436         1017 my $item_spec = $args->{$item_name}->{'src'};
1248 436         977 $item_spec =~ s/=for(.*)//ms;
1249 436         816 $pod_string .= "=item $item_name\n\n";
1250             # Get list of variable for this argument
1251 436         629 while ( my ($var_name, $var) = each %{$args->{$item_name}->{var}} ) {
  672         2901  
1252             # Get default for this variable
1253 236         423 for my $default_type ( 'default', 'opt_default' ) {
1254 472         528 my $var_default;
1255 472 100       6884 if (exists $var->{$default_type}) {
1256 132 100       679 if (ref($var->{$default_type}) eq 'ARRAY') {
    50          
1257 1         1 $var_default = join(' ', @{$var->{$default_type}});
  1         8  
1258             } elsif (ref($var->{$default_type}) eq '') {
1259 131         314 $var_default = $var->{$default_type};
1260             } else {
1261 0         0 carp 'Getopt::Euclid found an unexpected default value type';
1262             }
1263             } else {
1264 340         655 $var_default = 'none';
1265             }
1266 472         5022 $item_spec =~ s/$var_name\.$default_type/$var_default/g;
1267             }
1268             }
1269 436 100       2534 if ($item_spec =~ m/(\S+(\.(?:opt_)?default))/) {
1270 1         5 my ($reference, $default_type) = ($1, $2);
1271 1         7 _fail( "Invalid reference to field $reference in argument ".
1272             "description:\n$item_spec" );
1273             }
1274 435         837 $pod_string .= $item_spec;
1275             }
1276 102         368 $pod_string = "=over\n\n".$pod_string."=back\n\n";
1277 102         471 return $pod_string;
1278             }
1279              
1280              
1281             1; # Magic true value required at end of module
1282              
1283              
1284             =head1 NAME
1285              
1286             Getopt::Euclid - Executable Uniform Command-Line Interface Descriptions
1287              
1288             =head1 VERSION
1289              
1290             This document describes Getopt::Euclid version 0.4.5
1291              
1292             =head1 SYNOPSIS
1293              
1294             use Getopt::Euclid;
1295              
1296             if ($ARGV{-i}) {
1297             print "Interactive mode...\n";
1298             }
1299              
1300             for my $x (0..$ARGV{-size}{h}-1) {
1301             for my $y (0..$ARGV{-size}{w}-1) {
1302             do_something_with($x, $y);
1303             }
1304             }
1305              
1306             __END__
1307              
1308             =head1 NAME
1309              
1310             yourprog - Your program here
1311              
1312             =head1 VERSION
1313              
1314             This documentation refers to yourprog version 1.9.4
1315              
1316             =head1 USAGE
1317              
1318             yourprog [options] -s[ize]=<h>x<w> -o[ut][file] <file>
1319              
1320             =head1 REQUIRED ARGUMENTS
1321              
1322             =over
1323              
1324             =item -s[ize]=<h>x<w>
1325              
1326             Specify size of simulation
1327              
1328             =for Euclid:
1329             h.type: int > 0
1330             h.default: 24
1331             w.type: int >= 10
1332             w.default: 80
1333              
1334             =item -o[ut][file] <file>
1335              
1336             Specify output file
1337              
1338             =for Euclid:
1339             file.type: writable
1340             file.default: '-'
1341              
1342             =back
1343              
1344             =head1 OPTIONS
1345              
1346             =over
1347              
1348             =item -i
1349              
1350             Specify interactive simulation
1351              
1352             =item -l[[en][gth]] <l>
1353              
1354             Length of simulation. The default is l.default
1355              
1356             =for Euclid:
1357             l.type: int > 0
1358             l.default: 99
1359              
1360             =item --debug [<log_level>]
1361              
1362             Set the log level. Default is log_level.default but if you provide --debug,
1363             then it is log_level.opt_default.
1364              
1365             =for Euclid:
1366             log_level.type: int
1367             log_level.default: 0
1368             log_level.opt_default: 1
1369              
1370             =item --version
1371              
1372             =item --usage
1373              
1374             =item --help
1375              
1376             =item --man
1377              
1378             Print the usual program information
1379              
1380             =back
1381              
1382             Remainder of documentation starts here...
1383              
1384             =head1 AUTHOR
1385              
1386             Damian Conway (DCONWAY@CPAN.org)
1387              
1388             =head1 BUGS
1389              
1390             There are undoubtedly serious bugs lurking somewhere in this code.
1391             Bug reports and other feedback are most welcome.
1392              
1393             =head1 COPYRIGHT
1394              
1395             Copyright (c) 2005, Damian Conway. All Rights Reserved.
1396             This module is free software. It may be used, redistributed
1397             and/or modified under the terms of the Perl Artistic License
1398             (see http://www.perl.com/perl/misc/Artistic.html)
1399              
1400              
1401             =head1 DESCRIPTION
1402              
1403             Getopt::Euclid uses your program's own POD documentation to create a powerful
1404             command-line argument parser. This ensures that your program's documented interface
1405             and its actual interface always agree.
1406              
1407             The created command-line argument parser includes many features such as argument
1408             type checking, required arguments, exclusive arguments, optional arguments with
1409             default values, automatic usage message, ...
1410              
1411             To use the module, simply write the following at the top of your program:
1412              
1413             use Getopt::Euclid;
1414              
1415             This will cause Getopt::Euclid to be require'd and its import method will be
1416             called. It is important that the import method be allowed to run, so do not
1417             invoke Getopt::Euclid in the following manner:
1418              
1419             # Will not work
1420             use Getopt::Euclid ();
1421              
1422             When the module is loaded within a regular Perl program, it will:
1423              
1424             =over
1425              
1426             =item 1.
1427              
1428             locate any POD in the same *.pl file or its associated *.pod file.
1429              
1430             =item 2.
1431              
1432             extract information from that POD, most especially from
1433             the C<=head1 REQUIRED ARGUMENTS> and C<=head1 OPTIONS> sections,
1434              
1435             =item 3.
1436              
1437             build a parser that parses the arguments and options the POD specifies,
1438              
1439             =item 4.
1440              
1441             remove the command-line arguments from C<@ARGV> and parse them, and
1442              
1443             =item 5.
1444              
1445             put the results in the global C<%ARGV> variable (or into specifically named
1446             optional variables, if you request that -- see L<Exporting option variables>).
1447              
1448             =back
1449              
1450             As a special case, if the module is loaded within some other module
1451             (i.e. from within a C<.pm> file), it still locates and extracts POD
1452             information, but instead of parsing C<@ARGV> immediately, it caches that
1453             information and installs an C<import()> subroutine in the caller module.
1454             This new C<import()> acts just like Getopt::Euclid's own import, except
1455             that it adds the POD from the caller module to the POD of the callee.
1456              
1457             All of which just means you can put some or all of your CLI specification
1458             in a module, rather than in the application's source file.
1459             See L<Module interface> for more details.
1460              
1461             =head1 INTERFACE
1462              
1463             =head2 Program interface
1464              
1465             You write:
1466              
1467             use Getopt::Euclid;
1468              
1469             and your command-line is parsed automagically.
1470              
1471             =head2 Module interface
1472              
1473             =over
1474              
1475             =item import()
1476              
1477             You write:
1478              
1479             use Getopt::Euclid;
1480              
1481             and your module will then act just like Getopt::Euclid (i.e. you can use
1482             your module I<instead> of Getopt::Euclid>, except that your module's POD
1483             will also be prepended to the POD of any module that loads yours. In
1484             other words, you can use Getopt::Euclid in a module to create a standard
1485             set of CLI arguments, which can then be added to any application simply
1486             by loading your module.
1487              
1488             To accomplish this trick Getopt::Euclid installs an C<import()>
1489             subroutine in your module. If your module already has an C<import()>
1490             subroutine defined, terrible things happen. So do not do that.
1491              
1492             You may also short-circuit the import method within your calling program to
1493             have the POD from several modules included for argument parsing.
1494              
1495             use Module1::Getopt (); # No argument parsing
1496             use Module2::Getopt (); # No argument parsing
1497             use Getopt::Euclid; # Arguments parsed
1498              
1499             =item process_args()
1500              
1501             Alternatively, to parse arguments from a source different from C<@ARGV>, use the
1502             C<process_args()> subroutine.
1503              
1504             use Getopt::Euclid qw(:defer);
1505             my @args = ( '-in', 'file.txt', '-out', 'results.txt' );
1506             Getopt::Euclid->process_args(\@args);
1507              
1508             If you want to use the :minimal or :vars mode in this type of scenario, you can
1509             pass extra options to C<process_args()>:
1510              
1511             use Getopt::Euclid qw(:defer);
1512             my @args = ( '-in', 'file.txt', '-out', 'results.txt' );
1513             Getopt::Euclid->process_args(\@args, {-minimal => 1, -vars => 'prefix_'});
1514              
1515             This is particularly when you plan on processing POD manually.
1516              
1517             =item process_pods()
1518              
1519             Similarly, to parse argument specifications from a source different than the
1520             current script (and its dependencies), use the C<process_pods()> subroutine.
1521              
1522             use Getopt::Euclid ();
1523             my @pods = ( 'script.pl', 'Module.pm' );
1524             $Getopt::Euclid::MAN = Getopt::Euclid->process_pods(\@pods, {-strict => 1});
1525             my @args = ( '-in', 'file.txt', '-out', 'results.txt' );
1526             Getopt::Euclid->process_args(\@args);
1527              
1528             By default, this method will look for .pod files associated with the given .pl
1529             and .pm files and use these .pod files preferentially when available. Set
1530             -strict to 1 to only use the given files.
1531              
1532             =back
1533              
1534             =head2 POD interface
1535              
1536             This is where all the action is. POD markup can be placed in a .pod file that
1537             has the same prefix as the corresponding Perl file. Alternatively, POD can be
1538             inserted anywhere in the Perl code, but is typically added either after an
1539             __END__ statement (like in the L<SYNOPSIS>), or interspersed in the code:
1540              
1541             use Getopt::Euclid;
1542              
1543             =head1 NAME
1544              
1545             yourprog - Your program here
1546              
1547             =head1 REQUIRED ARGUMENTS
1548              
1549             =over
1550              
1551             =item -s[ize]=<h>x<w>
1552              
1553             Specify size of simulation
1554              
1555             =for Euclid:
1556             h.type: int > 0
1557             h.default: 24
1558             w.type: int >= 10
1559             w.default: 80
1560              
1561             =back
1562              
1563             =head1 OPTIONS
1564              
1565             =over
1566              
1567             =item -i
1568              
1569             Specify interactive simulation
1570              
1571             =back
1572              
1573             =cut
1574              
1575             # Getopt::Euclid has parsed commandline parameters and stored them in %ARGV
1576              
1577             if ($ARGV{-i}) {
1578             print "Interactive mode...\n";
1579             }
1580              
1581             for my $x (0..$ARGV{-size}{h}-1) {
1582             for my $y (0..$ARGV{-size}{w}-1) {
1583             do_something_with($x, $y);
1584             }
1585             }
1586              
1587             When Getopt::Euclid is loaded in a non-C<.pm> file, it searches that file for
1588             the following POD documentation:
1589              
1590             =over
1591              
1592             =item =head1 NAME
1593              
1594             Getopt::Euclid ignores the name specified here. In fact, if you use the
1595             standard C<--help>, C<--usage>, C<--man>, C<--podfile>, or C<--version>
1596             arguments (see L<Standard arguments>), the module replaces the name specified
1597             in this POD section with the actual name by which the program was invoked
1598             (i.e. with C<$0>).
1599              
1600             =item =head1 USAGE
1601              
1602             Getopt::Euclid ignores the usage line specified here. If you use the
1603             standard C<--help>, C<--usage>, C<--man> or C<--podfile> arguments, the
1604             module replaces the usage line specified in this POD section with a usage
1605             line that reflects the actual interface that the module has constructed.
1606              
1607             =item =head1 VERSION
1608              
1609             Getopt::Euclid extracts the current version number from this POD section.
1610             To do that it simply takes the first substring that matches
1611             I<< <digit> >>.I<< <digit> >> or I<< <digit> >>_I<< <digit> >>. It also
1612             accepts one or more additional trailing .I<< <digit> >> or _I<< <digit> >>,
1613             allowing for multi-level and "alpha" version numbers such as:
1614              
1615             =head1 VERSION
1616            
1617             This is version 1.2.3
1618              
1619             or:
1620              
1621             =head1 VERSION
1622            
1623             This is alpha release 1.2_34
1624              
1625             You may also specify the version number in your code. However, in order for
1626             Getopt::Euclid to properly read it, it must be in a C<BEGIN> block:
1627              
1628             BEGIN { use version; our $VERSION = qv('1.2.3') }
1629             use Getopt::Euclid;
1630              
1631             Euclid stores the version as C<$Getopt::Euclid::SCRIPT_VERSION>.
1632              
1633             =item =head1 REQUIRED ARGUMENTS
1634              
1635             Getopt::Euclid uses the specifications in this POD section to build a
1636             parser for command-line arguments. That parser requires that every one
1637             of the specified arguments is present in any command-line invocation.
1638             See L<Specifying arguments> for details of the specification syntax.
1639              
1640             The actual headings that Getopt::Euclid can recognize here are:
1641              
1642             =head1 [STANDARD|STD|PROGRAM|SCRIPT|CLI|COMMAND[-| ]LINE] [REQUIRED|MANDATORY] [PARAM|PARAMETER|ARG|ARGUMENT][S]
1643              
1644             B<Caveat:> Do not put additional subheadings (=headX) inside the REQUIRED ARGUMENTS
1645             section.
1646              
1647             =item =head1 OPTIONS
1648              
1649             Getopt::Euclid uses the specifications in this POD section to build a
1650             parser for command-line arguments. That parser does not require that any
1651             of the specified arguments is actually present in a command-line invocation.
1652             Again, see L<Specifying arguments> for details of the specification syntax.
1653              
1654             Typically a program will specify both C<REQUIRED ARGUMENTS> and C<OPTIONS>,
1655             but there is no requirement that it supply both, or either.
1656              
1657             The actual headings that Getopt::Euclid recognizes here are:
1658              
1659             =head1 [STANDARD|STD|PROGRAM|SCRIPT|CLI|COMMAND[-| ]LINE] OPTION[AL|S] [PARAM|PARAMETER|ARG|ARGUMENT][S]
1660              
1661             B<Caveat:> Do not put additional subheadings (=headX) inside the REQUIRED ARGUMENTS
1662             section.
1663              
1664             =item =head1 COPYRIGHT
1665              
1666             Getopt::Euclid prints this section whenever the standard C<--version> option
1667             is specified on the command-line.
1668              
1669             The actual heading that Getopt::Euclid recognizes here is any heading
1670             containing any of the words "COPYRIGHT", "LICENCE", or "LICENSE".
1671              
1672             =back
1673              
1674             =head2 Specifying arguments
1675              
1676             Each required or optional argument is specified in the POD in the following
1677             format:
1678              
1679             =item ARGUMENT_STRUCTURE
1680              
1681             ARGUMENT_DESCRIPTION
1682              
1683             =for Euclid:
1684             ARGUMENT_OPTIONS
1685             PLACEHOLDER_CONSTRAINTS
1686              
1687             =head3 Argument structure
1688              
1689             =over
1690              
1691             =item *
1692              
1693             Each argument is specified as an C<=item>.
1694              
1695             =item *
1696              
1697             Any part(s) of the
1698             specification that appear in square brackets are treated as optional.
1699              
1700             =item *
1701              
1702             Any parts that appear in angle brackets are placeholders for actual
1703             values that must be specified on the command-line.
1704              
1705             =item *
1706              
1707             Any placeholder that is immediately followed by C<...> may be repeated as many
1708             times as desired.
1709              
1710             =item *
1711              
1712             Any whitespace in the structure specifies that any amount of whitespace
1713             (including none) is allowed at the same position on the command-line.
1714              
1715             =item *
1716              
1717             A vertical bar indicates the start of an alternative variant of the argument.
1718              
1719             =back
1720              
1721             For example, the argument specification:
1722              
1723             =item -i[n] [=] <file> | --from <file>
1724              
1725             indicates that any of the following may appear on the command-line:
1726              
1727             -idata.txt -i data.txt -i=data.txt -i = data.txt
1728            
1729             -indata.txt -in data.txt -in=data.txt -in = data.txt
1730              
1731             --from data.text
1732              
1733             as well as any other combination of whitespacing.
1734              
1735             Any of the above variations would cause all three of:
1736              
1737             $ARGV{'-i'}
1738             $ARGV{'-in'}
1739             $ARGV{'--from'}
1740              
1741             to be set to the string C<'data.txt'>.
1742              
1743             You could allow the optional C<=> to also be an optional colon by specifying:
1744              
1745             =item -i[n] [=|:] <file>
1746              
1747             Optional components may also be nested, so you could write:
1748              
1749             =item -i[n[put]] [=] <file>
1750              
1751             which would allow C<-i>, C<-in>, and C<-input> as synonyms for this
1752             argument and would set all three of C<$ARGV{'-i'}>, C<$ARGV{'-in'}>, and
1753             C<$ARGV{'-input'}> to the supplied file name.
1754              
1755             The point of setting every possible variant within C<%ARGV> is that this
1756             allows you to use a single key (say C<$ARGV{'-input'}>, regardless of
1757             how the argument is actually specified on the command-line.
1758              
1759             =head2 Repeatable arguments
1760              
1761             Normally Getopt::Euclid only accepts each specified argument once, the first
1762             time it appears in @ARGV. However, you can specify that an argument may appear
1763             more than once, using the C<repeatable> option:
1764              
1765             =item file=<filename>
1766              
1767             =for Euclid:
1768             repeatable
1769              
1770             When an argument is marked repeatable the corresponding entry of C<%ARGV> will
1771             not contain a single value, but rather an array reference. If the argument also
1772             has L<Multiple placeholders>, then the corresponding entry in C<%ARGV> will be
1773             an array reference with each array entry being a hash reference.
1774              
1775             =head2 Boolean arguments
1776              
1777             If an argument has no placeholders it is treated as a boolean switch and its
1778             entry in C<%ARGV> will be true if the argument appeared in C<@ARGV>.
1779              
1780             For a boolean argument, you can also specify variations that are I<false>, if
1781             they appear. For example, a common idiom is:
1782              
1783             =item --print
1784              
1785             Print results
1786              
1787             =item --noprint
1788              
1789             Do not print results
1790              
1791             These two arguments are effectively the same argument, just with opposite
1792             boolean values. However, as specified above, only one of C<$ARGV{'--print'}>
1793             and C<$ARGV{'--noprint'}> will be set.
1794              
1795             As an alternative you can specify a single argument that accepts either value
1796             and sets both appropriately:
1797              
1798             =item --[no]print
1799              
1800             [Do not] print results
1801              
1802             =for Euclid:
1803             false: --noprint
1804              
1805             With this specification, if C<--print> appears in C<@ARGV>, then
1806             C<$ARGV{'--print'}> will be true and C<$ARGV{'--noprint'}> will be false.
1807             On the other hand, if C<--noprint> appears in C<@ARGV>, then
1808             C<$ARGV{'--print'}> will be false and C<$ARGV{'--noprint'}> will be true.
1809              
1810             The specified false values can follow any convention you wish:
1811              
1812             =item [+|-]print
1813              
1814             =for Euclid:
1815             false: -print
1816              
1817             or:
1818              
1819             =item -report[_no[t]]
1820              
1821             =for Euclid:
1822             false: -report_no[t]
1823              
1824             et cetera.
1825              
1826             =head2 Multiple placeholders
1827              
1828             An argument can have two or more placeholders:
1829              
1830             =item -size <h> <w>
1831              
1832             The corresponding command line argument would then have to provide two values:
1833              
1834             -size 24 80
1835              
1836             Multiple placeholders can optionally be separated by literal characters
1837             (which must then appear on the command-line). For example:
1838              
1839             =item -size <h>x<w>
1840              
1841             would then require a command-line of the form:
1842              
1843             -size 24x80
1844              
1845             If an argument has two or more placeholders, the corresponding entry in
1846             C<%ARGV> becomes a hash reference, with each of the placeholder names as one
1847             key. That is, the above command-line would set both C<$ARGV{'-size'}{'h'}> and
1848             C<$ARGV{'-size'}{'w'}>.
1849              
1850             =head2 Optional placeholders
1851              
1852             Placeholders can be specified as optional as well:
1853              
1854             =item -size <h> [<w>]
1855              
1856             This specification then allows either:
1857              
1858             -size 24
1859              
1860             or:
1861              
1862             -size 24 80
1863              
1864             on the command-line. If the second placeholder value is not provided, the
1865             corresponding C<$ARGV{'-size'}{'w'}> entry is set to C<undef>. See also
1866             L<Placeholder defaults>.
1867              
1868             =head2 Unflagged placeholders
1869              
1870             If an argument consists of a single placeholder with no "flag" marking it:
1871              
1872             =item <filename>
1873              
1874             then the corresponding entry in C<%ARG> will have a key the same as the
1875             placeholder (including the surrounding angle brackets):
1876              
1877             if ($ARGV{'<filename>'} eq '-') {
1878             $fh = \*STDIN;
1879             }
1880              
1881             The same is true for any more-complicated arguments that begin with a
1882             placeholder:
1883              
1884             =item <h> [x <w>]
1885              
1886             The only difference in the more-complex cases is that, if the argument
1887             has any additional placeholders, the entire entry in C<%ARGV> becomes a hash:
1888              
1889             my $total_size
1890             = $ARGV{'<h>'}{'h'} * $ARGV{'<h>'}{'w'}
1891              
1892             Note that, as in earlier multi-placeholder examples, the individual second-
1893             level placeholder keys I<do not> retain their angle-brackets.
1894              
1895             =head2 Repeated placeholders
1896              
1897             Any placeholder that is immediately followed by C<...>, like so:
1898              
1899             =item -lib <file>...
1900              
1901             =for Euclid:
1902             file.type: readable
1903              
1904             will match at least once, but as many times as possible before encountering
1905             the next argument on the command-line. This allows to specify multiple values
1906             for an argument, for example:
1907              
1908             -lib file1.txt file2.txt
1909              
1910             An unconstrained repeated unflagged placeholder (see L<Placeholder constraints>
1911             and L<Unflagged placeholders>) will consume the rest of the command-line, and
1912             so should be specified last in the POD
1913              
1914             =item -n <name>
1915              
1916             =item <offset>...
1917              
1918             =for Euclid:
1919             offset.type: 0+int
1920              
1921             and on the command-line:
1922              
1923             -n foobar 1 5 0 23
1924              
1925             If a placeholder is repeated, the corresponding entry in C<%ARGV>
1926             will then be an array reference, with each individual placeholder match
1927             in a separate element. For example:
1928              
1929             for my $lib (@{ $ARGV{'-lib'} }) {
1930             add_lib($lib);
1931             }
1932              
1933             warn "First offset is: $ARGV{'<offsets>'}[0]";
1934             my $first_offset = shift @{ $ARGV{'<offsets>'} };
1935              
1936             =head2 Placeholder constraints
1937              
1938             You can specify that the value provided for a particular placeholder
1939             must satisfy a particular set of restrictions by using a C<=for Euclid>
1940             block. For example:
1941              
1942             =item -size <h>x<w>
1943              
1944             =for Euclid:
1945             h.type: integer
1946             w.type: integer
1947              
1948             specifies that both the C<< <h> >> and C<< <w> >> must be given integers.
1949             You can also specify an operator expression after the type name:
1950              
1951             =for Euclid:
1952             h.type: integer > 0
1953             w.type: number <= 100
1954              
1955             specifies that C<< <h> >> has to be given an integer that is greater than zero,
1956             and that C<< <w> >> has to be given a number (not necessarily an integer)
1957             that is no more than 100.
1958              
1959             These type constraints have two alternative syntaxes:
1960              
1961             PLACEHOLDER.type: TYPE BINARY_OPERATOR EXPRESSION
1962              
1963             as shown above, and the more general:
1964              
1965             PLACEHOLDER.type: TYPE [, EXPRESSION_INVOLVING(PLACEHOLDER)]
1966              
1967             Using the second syntax, you could write the previous constraints as:
1968              
1969             =for Euclid:
1970             h.type: integer, h > 0
1971             w.type: number, w <= 100
1972              
1973             In other words, the first syntax is just sugar for the most common case of the
1974             second syntax. The expression can be as complex as you wish and can refer to
1975             the placeholder as many times as necessary:
1976              
1977             =for Euclid:
1978             h.type: integer, h > 0 && h < 100
1979             w.type: number, Math::is_prime(w) || w % 2 == 0
1980              
1981             Note that the expressions are evaluated in the C<package main> namespace,
1982             so it is important to qualify any subroutines that are not in that namespace.
1983             Furthermore, any subroutines used must be defined (or loaded from a module)
1984             I<before> the C<use Getopt::Euclid> statement.
1985              
1986             You can also use constraints that involve variables. You must use the :defer
1987             mode and the variables must be globally accessible:
1988              
1989             use Getopt::Euclid qw(:defer);
1990             our $MIN_VAL = 100;
1991             Getopt::Euclid->process_args(\@ARGV);
1992              
1993             __END__
1994              
1995             =head1 OPTIONS
1996              
1997             =over
1998              
1999             =item --magnitude <magnitude>
2000              
2001             =for Euclid
2002             magnitude.type: number, magnitude > $MIN_VAL
2003              
2004             =back
2005              
2006              
2007             =head2 Standard placeholder types
2008              
2009             Getopt::Euclid recognizes the following standard placeholder types:
2010              
2011             Name Placeholder value... Synonyms
2012             ============ ==================== ================
2013              
2014             integer ...must be an integer int i
2015              
2016             +integer ...must be a positive +int +i
2017             integer
2018             (same as: integer > 0)
2019              
2020             0+integer ...must be a positive 0+int 0+i
2021             integer or zero
2022             (same as: integer >= 0)
2023              
2024             number ...must be an number num n
2025              
2026             +number ...must be a positive +num +n
2027             number
2028             (same as: number > 0)
2029              
2030             0+number ...must be a positive 0+num 0+n
2031             number or zero
2032             (same as: number >= 0)
2033              
2034             string ...may be any string str s
2035             (default type)
2036              
2037             readable ...must be the name input in
2038             of a readable file
2039              
2040             writeable ...must be the name writable output out
2041             of a writeable file
2042             (or of a non-existent
2043             file in a writeable
2044             directory)
2045            
2046             /<regex>/ ...must be a string
2047             matching the specified
2048             pattern
2049              
2050             Since regular expressions are supported, you can easily match many more type of
2051             strings for placeholders by using the regular expressions available in Regexp::Common.
2052             If you do that, you may want to also use custom placeholder error messages (see
2053             L<Placeholder type errors>) since the messages would otherwise not be very
2054             informative to users.
2055              
2056             use Regexp::Common qw /zip/;
2057             use Getopt::Euclid;
2058              
2059             ...
2060              
2061             =item -p <postcode>
2062              
2063             Enter your postcode here
2064              
2065             =for Euclid:
2066             postcode.type: /$RE{zip}{France}/
2067             postcode.type.error: <postcode> must be a valid ZIP code
2068              
2069             =head2 Placeholder type errors
2070              
2071             If a command-line argument's placeholder value does not satisify the specified
2072             type, an error message is automatically generated. However, you can provide
2073             your own message instead, using the C<.type.error> specifier:
2074              
2075             =for Euclid:
2076             h.type: integer, h > 0 && h < 100
2077             h.type.error: <h> must be between 0 and 100 (not h)
2078              
2079             w.type: number, Math::is_prime(w) || w % 2 == 0
2080             w.type.error: Cannot use w for <w> (must be an even prime number)
2081              
2082             Whenever an explicit error message is provided, any occurrence within
2083             the message of the placeholder's unbracketed name is replaced by the
2084             placeholder's value (just as in the type test itself).
2085              
2086             =head2 Placeholder defaults
2087              
2088             You can also specify a default value for any placeholders that are not
2089             given values on the command-line (either because their argument is not
2090             provided at all, or because the placeholder is optional within the argument).
2091             For example:
2092              
2093             =item -size <h>[x<w>]
2094              
2095             Set the size of the simulation
2096              
2097             =for Euclid:
2098             h.default: 24
2099             w.default: 80
2100              
2101             This ensures that if no C<< <w> >> value is supplied:
2102              
2103             -size 20
2104              
2105             then C<$ARGV{'-size'}{'w'}> is set to 80. Likewise, of the C<-size> argument is
2106             omitted entirely, both C<$ARGV{'-size'}{'h'}> and C<$ARGV{'-size'}{'w'}> are set
2107             to their respective default values
2108              
2109             However, Getopt::Euclid also supports a second type of default, optional defaults,
2110             that apply only to flagged, optional placeholders.
2111              
2112             For example:
2113              
2114             =item --debug [<log_level>]
2115              
2116             Set the log level
2117              
2118             =for Euclid:
2119             log_level.type: int
2120             log_level.default: 0
2121             log_level.opt_default: 1
2122              
2123             This ensures that if the option C<< --debug >> is not specified, then
2124             C<$ARGV{'--debug'}> is set to 0, the regular default. But if no C<< <log_level> >>
2125             value is supplied:
2126              
2127             --debug
2128            
2129             then C<$ARGV{'--debug'}> is set to 1, the optional default.
2130              
2131              
2132             The default value can be any valid Perl compile-time expression:
2133              
2134             =item -pi=<pi value>
2135              
2136             =for Euclid:
2137             pi value.default: atan2(0,-1)
2138              
2139             You can refer to an argument default or optional default value in its POD entry
2140             as shown below:
2141              
2142             =item -size <h>[x<w>]
2143              
2144             Set the size of the simulation [default: h.default x w.default]
2145              
2146             =for Euclid:
2147             h.default: 24
2148             w.default: 80
2149              
2150             =item --debug <level>
2151            
2152             Set the debug level. The default is level.default if you supply --debug but
2153             omit a <level> value.
2154              
2155             =for Euclid:
2156             level.opt_default: 3
2157              
2158             Just like for L<Placeholder constraints>, you can also use variables to define
2159             default values. You must use the :defer mode and the variables must be globally
2160             accessible:
2161              
2162             use Getopt::Euclid qw(:defer);
2163             Getopt::Euclid->process_args(\@ARGV);
2164              
2165             __END__
2166              
2167             =head1 OPTIONS
2168              
2169             =over
2170              
2171             =item --home <home>
2172              
2173             Your project home. When omitted, this defaults to the location stored in
2174             the HOME environment variable.
2175              
2176             =for Euclid
2177             home.default: $ENV{'HOME'}
2178              
2179             =back
2180              
2181             =head2 Exclusive placeholders
2182              
2183             Some arguments can be mutually exclusive. In this case, it is possible to
2184             specify that a placeholder excludes a list of other placeholders, for example:
2185              
2186             =item -height <h>
2187              
2188             Set the desired height
2189              
2190             =item -width <w>
2191              
2192             Set the desired width
2193              
2194             =item -volume <v>
2195              
2196             Set the desired volume
2197              
2198             =for Euclid:
2199             v.excludes: h, w
2200             v.excludes.error: Either set the volume or the height and weight
2201              
2202             Specifying both placeholders at the same time on the command-line will
2203             generate an error. Note that the error message can be customized, as
2204             illustrated above.
2205              
2206             When using exclusive arguments that have default values, the default value of
2207             the placeholder with the .excludes statement has precedence over any other
2208             placeholders.
2209              
2210             =head2 Argument cuddling
2211              
2212             Getopt::Euclid allows any "flag" argument to be "cuddled". A flag
2213             argument consists of a single non- alphanumeric character, followed by a
2214             single alpha-numeric character:
2215              
2216             =item -v
2217              
2218             =item -x
2219              
2220             =item +1
2221              
2222             =item =z
2223              
2224             Cuddling means that two or more such arguments can be concatenated after a
2225             single common non-alphanumeric. For example:
2226              
2227             -vx
2228              
2229             Note, however, that only flags with the same leading non-alphanumeric can be
2230             cuddled together. Getopt::Euclid would not allow:
2231              
2232             -vxz
2233              
2234             This is because cuddling is recognized by progressively removing the second
2235             character of the cuddle. In other words:
2236              
2237             -vxz
2238              
2239             becomes:
2240              
2241             -v -xz
2242              
2243             which becomes:
2244              
2245             -v -x z
2246              
2247             which will fail, unless a C<z> argument has also been specified.
2248              
2249             On the other hand, if the argument:
2250              
2251             =item -e <cmd>
2252              
2253             had been specified, the module I<would> accept:
2254              
2255             -vxe'print time'
2256              
2257             as a cuddled version of:
2258              
2259             -v -x -e'print time'
2260              
2261             =head2 Exporting option variables
2262              
2263             By default, the module only stores arguments into the global %ARGV hash.
2264             You can request that options are exported as variables into the calling package
2265             using the special C<':vars'> specifier:
2266              
2267             use Getopt::Euclid qw( :vars );
2268              
2269             That is, if your program accepts the following arguments:
2270              
2271             -v
2272             --mode <modename>
2273             <infile>
2274             <outfile>
2275             --auto-fudge <factor> (repeatable)
2276             --also <a>...
2277             --size <w>x<h>
2278             --multiply <num1>x<num2> (repeatable)
2279              
2280             Then these variables will be exported
2281              
2282             $ARGV_v
2283             $ARGV_mode
2284             $ARGV_infile
2285             $ARGV_outfile
2286             @ARGV_auto_fudge
2287             @ARGV_also
2288             %ARGV_size # With entries $ARGV_size{w} and $ARGV_size{h}
2289             @ARGV_multiply # With entries that are hashref similar to \%ARGV_size
2290              
2291             For options that have multiple variants, only the longest variant is exported.
2292              
2293             The type of variable exported (scalar, hash, or array) is determined by the
2294             type of the corresponding value in C<%ARGV>. Command-line flags and arguments
2295             that take single values will produce scalars, arguments that take multiple
2296             values will produce hashes, and repeatable arguments will produce arrays.
2297              
2298             If you do not like the default prefix of "ARGV_", you can specify your own,
2299             such as "opt_", like this:
2300              
2301             use Getopt::Euclid qw( :vars<opt_> );
2302              
2303             The major advantage of using exported variables is that any misspelling of
2304             argument variables in your code will be caught at compile-time by
2305             C<use strict>.
2306              
2307             =head2 Standard arguments
2308              
2309             Getopt::Euclid automatically provides four standard arguments to any
2310             program that uses the module. The behaviours of these arguments are "hard-
2311             wired" and cannot be changed, not even by defining your own arguments of
2312             the same name.
2313              
2314             The standard arguments are:
2315              
2316             =over
2317              
2318             =item --usage usage()
2319              
2320             The --usage argument causes the program to print a short usage summary and exit.
2321             The C<Getopt::Euclid->usage()> subroutine provides access to the string of this
2322             message.
2323              
2324             =item --help help()
2325              
2326             The --help argument causes the program to take a longer usage summary (with
2327             a full list of required and optional arguments) provided in POD format by
2328             C<help()>, convert it to plaintext, display it and exit. The message is paged
2329             using IO::Pager::Page (or IO::Page) if possible.
2330              
2331             =item --man man()
2332              
2333             The --man argument causes the program to take the POD documentation for
2334             the program, provided by C<man()>, convert it to plaintext, display it and
2335             exit. The message is paged using IO::Pager::Page (or IO::Page) if possible.
2336              
2337             =item --podfile podfile()
2338              
2339             The --podfile argument is provided for authors. It causes the program to take
2340             the POD manual from C<man()>, write it in a .pod file with the same base name
2341             as the program, display the name of the output file and exit. These actions can
2342             also be executed by calling the C<podfile()> subroutine.This argument is not
2343             really a standard argument, but it is useful if the program's POD is to be
2344             passed to a POD converter because, among other things, any default value
2345             specified is interpolated and replaced by its value in the .pod file, contrary
2346             to in the program's .pl file.
2347              
2348             If you want to automate the creation of a POD file during the build process, you
2349             can edit you Makefile.PL or Build.PL file and add these lines:
2350              
2351             my @args = ($^X, '-Ilib', '/path/to/script', '--podfile');
2352             system(@args) == 0 or die "System call to '@args' failed:\n$?\n";
2353              
2354             If you use L<Module::Install> to bundle your script, you might be interested in
2355             using L<Module::Install::PodFromEuclid> to include the --podfile step into the
2356             installation process.
2357              
2358             =item --version version()
2359              
2360             The --version argument causes the program to print the version number of the
2361             program (as specified in the C<=head1 VERSION> section of the POD) and
2362             any copyright information (as specified in the C<=head1 COPYRIGHT>
2363             POD section) and then exit. The C<Getopt::Euclid->version()> subroutine provides
2364             access to the string of this message.
2365              
2366             =back
2367              
2368             =head2 Minimalist keys
2369              
2370             By default, the keys of C<%ARGV> will match the program's interface
2371             exactly. That is, if your program accepts the following arguments:
2372              
2373             -v
2374             --mode <modename>
2375             <infile>
2376             <outfile>
2377             --auto-fudge
2378              
2379             Then the keys that appear in C<%ARGV> will be:
2380              
2381             '-v'
2382             '--mode'
2383             '<infile>'
2384             '<outfile>'
2385             '--auto-fudge'
2386              
2387             In some cases, however, it may be preferable to have Getopt::Euclid set
2388             up those hash keys without "decorations". That is, to have the keys of
2389             C<%ARGV> be simply:
2390              
2391             'v'
2392             'mode'
2393             'infile'
2394             'outfile'
2395             'auto_fudge'
2396              
2397             You can arrange this by loading the module with the special C<':minimal_keys'>
2398             specifier:
2399              
2400             use Getopt::Euclid qw( :minimal_keys );
2401              
2402             Note that, in rare cases, using this mode may cause you to lose
2403             data (for example, if the interface specifies both a C<--step> and
2404             a C<< <step> >> option). The module throws an exception if this happens.
2405              
2406             =head2 Deferring argument parsing
2407              
2408             In some instances, you may want to avoid the parsing of arguments to take place
2409             as soon as your program is executed and Getopt::Euclid is loaded. For example,
2410             you may need to examine C<@ARGV> before it is processed (and emptied) by
2411             Getopt::Euclid. Or you may intend to pass your own arguments manually only
2412             using C<process_args()>.
2413              
2414             To defer the parsing of arguments, use the specifier C<':defer'>:
2415              
2416             use Getopt::Euclid qw( :defer );
2417             # Do something...
2418             Getopt::Euclid->process_args(\@ARGV);
2419              
2420             =head1 DIAGNOSTICS
2421              
2422             =head2 Compile-time diagnostics
2423              
2424             The following diagnostics are mainly caused by problems in the POD
2425             specification of the command-line interface:
2426              
2427             =over
2428              
2429             =item Getopt::Euclid was unable to access POD
2430              
2431             Something is horribly wrong. Getopt::Euclid was unable to read your
2432             program to extract the POD from it. Check your program's permissions,
2433             though it is a mystery how I<perl> was able to run the program in the
2434             first place, if it is not readable.
2435              
2436             =item .pm file cannot define an explicit import() when using Getopt::Euclid
2437              
2438             You tried to define an C<import()> subroutine in a module that was also
2439             using Getopt::Euclid. Since the whole point of using Getopt::Euclid in a
2440             module is to have it build an C<import()> for you, supplying your own
2441             C<import()> as well defeats the purpose.
2442              
2443             =item Unknown specification: %s
2444              
2445             You specified something in a C<=for Euclid> section that
2446             Getopt::Euclid did not understand. This is often caused by typos, or by
2447             reversing a I<placeholder>.I<type> or I<placeholder>.I<default>
2448             specification (that is, writing I<type>.I<placeholder> or
2449             I<default>.I<placeholder> instead).
2450              
2451             =item Unknown type (%s) in specification: %s
2452              
2453             =item Unknown .type constraint: %s
2454              
2455             Both these errors mean that you specified a type constraint that
2456             Getopt::Euclid did not recognize. This may have been a typo:
2457              
2458             =for Euclid
2459             count.type: inetger
2460              
2461             or else the module simply does not know about the type you specified:
2462              
2463             =for Euclid
2464             count.type: complex
2465              
2466             See L<Standard placeholder types> for a list of types that Getopt::Euclid
2467             I<does> recognize.
2468              
2469             =item Invalid .type constraint: %s
2470              
2471             You specified a type constraint that is not valid Perl. For example:
2472              
2473             =for Euclid
2474             max.type: integer not equals 0
2475              
2476             instead of:
2477              
2478             =for Euclid
2479             max.type: integer != 0
2480              
2481             =item Invalid .default value: %s
2482              
2483             You specified a default value that is not valid Perl. For example:
2484              
2485             =for Euclid
2486             curse.default: *$@!&
2487              
2488             instead of:
2489              
2490             =for Euclid
2491             curse.default: '*$@!&'
2492              
2493             =item Invalid .opt_default value: %s
2494              
2495             Same as previous diagnostic, but for optional defaults.
2496              
2497             =item Invalid reference to field %s.default in argument description: %s
2498              
2499             You referred to a default value in the description of an argument, but there
2500             is no such default. It may be a typo, or you may be referring to the default
2501             value for a different argument, e.g.:
2502              
2503             =item -a <age>
2504              
2505             An optional age. Default: years.default
2506              
2507             =for Euclid
2508             age.default: 21
2509              
2510             instead of:
2511              
2512             =item -a <age>
2513              
2514             An optional age. Default: age.default
2515              
2516             =for Euclid
2517             age.default: 21
2518              
2519             =item Invalid reference to field %s.opt_default in argument description: %s
2520              
2521             Same as previous diagnostic, but for optional defaults.
2522              
2523             =item Invalid .opt_default constraint: Placeholder <%s> must be optional
2524              
2525             You specified an optional default but the placeholder that it affects is not an
2526             optional placeholder. For example:
2527              
2528             =item -l[[en][gth]] <l>
2529              
2530             =for Euclid:
2531             l.opt_default: 123
2532              
2533             instead of:
2534              
2535             =item -l[[en][gth]] [<l>]
2536              
2537             =for Euclid:
2538             l.opt_default: 123
2539              
2540              
2541             =item Invalid .opt_default constraint: Parameter %s must have a flag
2542              
2543             You specified an optional default but the parameter that it affects is
2544             unflagged. For example:
2545              
2546             =item <length>
2547              
2548             =for Euclid:
2549             l.opt_default: 123
2550              
2551             instead of:
2552              
2553             =item -l [<length>]
2554              
2555             =for Euclid:
2556             l.opt_default: 123
2557              
2558             =item Invalid .excludes value for variable %s: <%s> does not exist
2559              
2560             You specified to exclude a variable that was not seen in the POD. Make sure
2561             that this is not a typo.
2562              
2563             =item Invalid constraint: %s (No <%s> placeholder in argument: %s)
2564              
2565             You attempted to define a C<.type> constraint for a placeholder that
2566             did not exist. Typically this is the result of the misspelling of a
2567             placeholder name:
2568              
2569             =item -foo <bar>
2570              
2571             =for Euclid:
2572             baz.type: integer
2573              
2574             or a C<=for Euclid:> that has drifted away from its argument:
2575              
2576             =item -foo <bar>
2577              
2578             =item -verbose
2579              
2580             =for Euclid:
2581             bar.type: integer
2582              
2583             =item Getopt::Euclid loaded a second time
2584              
2585             You tried to load the module twice in the same program.
2586             Getopt::Euclid does not work that way. Load it only once.
2587              
2588             =item Unknown mode ('%s')
2589              
2590             The only argument that a C<use Getopt::Euclid> command accepts is
2591             C<':minimal_keys'> (see L<Minimalist keys>). You specified something
2592             else instead (or possibly forgot to put a semicolon after C<use
2593             Getopt::Euclid>).
2594              
2595             =item Internal error: minimalist mode caused arguments '%s' and '%s' to clash
2596              
2597             Minimalist mode removes certain characters from the keys hat are
2598             returned in C<%ARGV>. This can mean that two command-line options (such
2599             as C<--step> and C<< <step> >>) map to the same key (i.e. C<'step'>).
2600             This in turn means that one of the two options has overwritten the other
2601             within the C<%ARGV> hash. The program developer should either turn off
2602             C<':minimal_keys'> mode within the program, or else change the name of
2603             one of the options so that the two no longer clash.
2604              
2605             =back
2606              
2607             =head2 Run-time diagnostics
2608              
2609             The following diagnostics are caused by problems in parsing the command-line
2610              
2611             =over
2612              
2613             =item Missing required argument(s): %s
2614              
2615             At least one argument specified in the C<REQUIRED ARGUMENTS> POD section
2616             was not present on the command-line.
2617              
2618             =item Invalid %s argument. %s must be %s but the supplied value (%s) is not.
2619              
2620             Getopt::Euclid recognized the argument you were trying to specify on the
2621             command-line, but the value you gave to one of that argument's placeholders
2622             was of the wrong type.
2623              
2624             =item Unknown argument: %s
2625              
2626             Getopt::Euclid did not recognize an argument you were trying to specify on the
2627             command-line. This is often caused by command-line typos or an incomplete
2628             interface specification.
2629              
2630             =back
2631              
2632             =head1 CONFIGURATION AND ENVIRONMENT
2633              
2634             Getopt::Euclid requires no configuration files or environment variables.
2635              
2636             =head1 DEPENDENCIES
2637              
2638             =over
2639              
2640             =item *
2641              
2642             version
2643              
2644             =item *
2645              
2646             Pod::Select
2647              
2648             =item *
2649              
2650             Pod::PlainText
2651              
2652             =item *
2653              
2654             File::Basename
2655              
2656             =item *
2657              
2658             File::Spec::Functions
2659              
2660             =item *
2661              
2662             List::Util
2663              
2664             =item *
2665              
2666             Text::Balanced
2667              
2668             =item *
2669              
2670             IO::Pager::Page (recommended)
2671              
2672             =back
2673              
2674             =head1 INCOMPATIBILITIES
2675              
2676             Getopt::Euclid may not work properly with POD in Perl files that have been
2677             converted into an executable with PerlApp or similar software. A possible
2678             workaround may be to move the POD to a __DATA__ section or a separate .pod file.
2679              
2680             =head1 BUGS AND LIMITATIONS
2681              
2682             Please report any bugs or feature requests to
2683             C<bug-getopt-euclid@rt.cpan.org>, or through the web interface at
2684             L<https://rt.cpan.org/Public/Dist/Display.html?Name=Getopt-Euclid>.
2685              
2686             Getopt::Euclid has a development repository on Sourceforge.net at
2687             L<http://sourceforge.net/scm/?type=git&group_id=259291> in which the code is
2688             managed by Git. Feel free to clone this repository and push patches! To get started:
2689             git clone L<git://getopt-euclid.git.sourceforge.net/gitroot/getopt-euclid/getopt-euclid>)
2690             git branch 0.2.x origin/0.2.x
2691             git checkout 0.2.x
2692              
2693             =head1 AUTHOR
2694              
2695             Damian Conway C<< <DCONWAY@cpan.org> >>
2696              
2697             Florent Angly C<< <florent.angly@gmail.com> >>
2698              
2699             =head1 LICENCE AND COPYRIGHT
2700              
2701             Copyright (c) 2005, Damian Conway C<< <DCONWAY@cpan.org> >>. All rights reserved.
2702              
2703             This module is free software; you can redistribute it and/or
2704             modify it under the same terms as Perl itself.
2705              
2706             =head1 DISCLAIMER OF WARRANTY
2707              
2708             BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
2709             FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
2710             OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
2711             PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
2712             EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2713             WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
2714             ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
2715             YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
2716             NECESSARY SERVICING, REPAIR, OR CORRECTION.
2717              
2718             IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
2719             WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
2720             REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
2721             LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
2722             OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
2723             THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
2724             RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
2725             FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
2726             SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
2727             SUCH DAMAGES.