File Coverage

blib/lib/Getopt/Flex.pm
Criterion Covered Total %
statement 14 16 87.5
branch n/a
condition n/a
subroutine 6 6 100.0
pod n/a
total 20 22 90.9


line stmt bran cond sub pod time code
1             package Getopt::Flex;
2             BEGIN {
3 15     15   491875 $Getopt::Flex::VERSION = '1.07';
4             }
5              
6             # ABSTRACT: Option parsing, done different.
7              
8 15     15   133 use strict; #shut up cpants
  15         29  
  15         469  
9 15     15   71 use warnings; #shut up cpants
  15         27  
  15         391  
10 15     15   11386 use Clone;
  15         50950  
  15         951  
11 15     15   12714 use Hash::Merge qw(merge);
  15         47830  
  15         1087  
12 15     15   27860 use Moose;
  0            
  0            
13             use MooseX::StrictConstructor;
14             use Getopt::Flex::Config;
15             use Getopt::Flex::Spec;
16              
17             #return values for the function that
18             #determines the type of switch it is
19             #inspecting
20             my $_ST_LONG = 1;
21             my $_ST_SHORT = 2;
22             my $_ST_BUNDLED = 3;
23             my $_ST_NONE = 4;
24              
25             #the raw spec defining the options to be parsed
26             #and how they are to be handled
27             has 'spec' => (
28             is => 'ro',
29             isa => 'HashRef[HashRef[Str|CodeRef|ScalarRef|ArrayRef|HashRef]]',
30             required => 1,
31             writer => '_set_spec',
32             );
33              
34             #the parsed Getopt::Flex::Spec object
35             has '_spec' => (
36             is => 'rw',
37             isa => 'Getopt::Flex::Spec',
38             init_arg => undef,
39             );
40              
41             #the raw config defining any relevant configuration
42             #parameters
43             has 'config' => (
44             is => 'ro',
45             isa => 'HashRef[Str]',
46             default => sub { {} },
47             );
48              
49             #the parsed Getopt::Flex::Config object
50             has '_config' => (
51             is => 'rw',
52             isa => 'Getopt::Flex::Config',
53             init_arg => undef,
54             );
55              
56             #the arguments passed to the calling script,
57             #clones @ARGV so it won't be modified
58             has '_args' => (
59             is => 'rw',
60             isa => 'ArrayRef',
61             init_arg => undef,
62             );
63              
64             #an array of the valid switches passed to the script
65             has 'valid_args' => (
66             is => 'ro',
67             isa => 'ArrayRef[Str]',
68             writer => '_set_valid_args',
69             reader => '_get_valid_args',
70             init_arg => undef,
71             default => sub { [] },
72             );
73              
74             #an array of the invalid switches passed to the script
75             has 'invalid_args' => (
76             is => 'ro',
77             isa => 'ArrayRef[Str]',
78             writer => '_set_invalid_args',
79             reader => '_get_invalid_args',
80             init_arg => undef,
81             default => sub { [] },
82             );
83              
84             #an array of anything that wasn't a switch that was encountered
85             has 'extra_args' => (
86             is => 'ro',
87             isa => 'ArrayRef[Str]',
88             writer => '_set_extra_args',
89             reader => '_get_extra_args',
90             init_arg => undef,
91             default => sub { [] },
92             );
93            
94             #error message, for reporting more info about errors
95             has 'error' => (
96             is => 'ro',
97             isa => 'Str',
98             writer => '_set_error',
99             reader => 'get_error',
100             init_arg => undef,
101             default => '',
102             );
103              
104              
105             sub BUILD {
106             my $self = shift;
107            
108             #set args from argv
109             $self->_args(Clone::clone(\@ARGV));
110            
111             #create the configuration
112             $self->_config(Getopt::Flex::Config->new($self->config()));
113            
114             #create the spec
115             $self->_spec(Getopt::Flex::Spec->new({ spec => $self->spec(), config => $self->_config() }));
116            
117             return;
118             }
119              
120              
121             sub getopts {
122             my ($self) = @_;
123            
124             my @args = @{$self->_args()};
125             my @valid_args = ();
126             my @invalid_args = ();
127             my @extra_args = ();
128            
129             my $non_opt_mode = $self->_config()->non_option_mode();
130            
131             PROCESS: for(my $i = 0; $i <= $#args; ++$i) {
132             my $item = $args[$i];
133            
134             #stop processing immediately
135             last if $item =~ /^--$/;
136            
137             #not a switch, so an extra argument
138             if(!$self->_is_switch($item)) {
139             push(@extra_args, $item);
140            
141             if($non_opt_mode eq 'STOP_RET_0') {
142             $self->_set_error("Encountered illegal item $item");
143             return 0;
144             } elsif($non_opt_mode eq 'STOP') {
145             last;
146             } elsif($non_opt_mode eq 'VALUE_RET_0') {
147             $self->_set_error("Encountered illegal value $item");
148             return 0;
149             }
150              
151             next;
152             }
153            
154             #if we have a switch, parse it and return any values we encounter
155             #there are a few ways that values are returned: as scalars, when
156             #the accompanying value was not present in the switch passed (i.e.
157             #the form "-f bar" was encountered and not "-fbar" or "-f=bar").
158             #If an array is returned, the value accompanying the switch was
159             #found with it, and $arr[0] contains the switch name and $arr[1]
160             #contains the value found. If a hash is returned, it was a bundled
161             #switch, and the keys are switch names and the values are those
162             #values (if any) that were found.
163             my $ret = $self->_parse_switch($item);
164            
165             #handle scalar returns
166             if(ref($ret) eq 'SCALAR') {
167             $ret = $$ret; #get our var
168            
169             if(!$self->_spec()->check_switch($ret)) {
170             push(@invalid_args, $ret);
171             if($non_opt_mode eq 'STOP_RET_0') {
172             $self->_set_error("Encountered illegal switch $ret");
173             return 0;
174             } elsif($non_opt_mode eq 'STOP') {
175             last;
176             } elsif($non_opt_mode eq 'SWITCH_RET_0') {
177             $self->_set_error("Encountered illegal switch $ret");
178             return 0;
179             }
180             next;
181             }
182            
183             if($self->_spec()->switch_requires_val($ret)) { #requires a value?
184             #peek forward in args, because we didn't find the
185             #necessary value with the switch
186             if(defined($args[$i+1]) && !$self->_is_switch($args[$i+1])) {
187             if($self->_spec()->set_switch($ret, $args[$i+1])) {
188             push(@valid_args, $ret);
189             ++$i;
190             } else {
191             $self->_set_error($self->_spec()->get_switch_error($ret));
192             return 0;
193             }
194             } else {
195             $self->_set_error("switch $ret requires value, but none given\n");
196             return 0;
197             }
198             } else { #doesn't require a value, so just use 1
199             if($self->_spec()->set_switch($ret, 1)) {
200             push(@valid_args, $ret);
201             } else {
202             $self->_set_error($self->_spec()->get_switch_error($ret));
203             return 0;
204             }
205             }
206             #handle hash returns
207             } elsif(ref($ret) eq 'HASH') {
208             my %rh = %{$ret}; #get the hash
209             BUNDLED: foreach my $key (keys %rh) {
210             if(!$self->_spec()->check_switch($key)) {
211             if($key ne '~~last') {
212             push(@invalid_args, $key);
213             if($non_opt_mode eq 'STOP_RET_0') {
214             $self->_set_error("Encountered illegal switch $key");
215             return 0;
216             } elsif($non_opt_mode eq 'STOP') {
217             last PROCESS;
218             } elsif($non_opt_mode eq 'SWITCH_RET_0') {
219             $self->_set_error("Encountered illegal switch $key");
220             return 0;
221             }
222             }
223             next BUNDLED;
224             }
225            
226             if(defined($rh{$key})) {
227             if($self->_spec()->set_switch($key, $rh{$key})) {
228             push(@valid_args, $key);
229             next BUNDLED;
230             } else {
231             $self->_set_error($self->_spec()->get_switch_error($key));
232             return 0;
233             }
234             }
235            
236             if(!$self->_spec()->switch_requires_val($key)) {
237             if($self->_spec()->set_switch($key, 1)) {
238             push(@valid_args, $key);
239             next BUNDLED;
240             } else {
241             $self->_set_error($self->_spec()->get_switch_error($key));
242             return 0;
243             }
244             }
245            
246             if($key ne $rh{'~~last'}) {
247             #FFFUUUU
248             $self->_set_error("switch $key requires value, but none given\n");
249             return 0;
250             }
251            
252             if($self->_is_switch($args[$i+1])) {
253             self->_set_error("switch $key requires value, but none given\n");
254             return 0;
255             }
256            
257             #okay, peek
258             if($self->_spec()->set_switch($key, $args[$i+1])) {
259             push(@valid_args, $key);
260             ++$i;
261             } else {
262             $self->_set_error($self->_spec()->get_switch_error($key));
263             return 0;
264             }
265             }
266             #handle array returns
267             } elsif(ref($ret) eq 'ARRAY') {
268             my @arr = @{$ret}; #get the array
269             if($#arr != 1) {
270             #this would be an error in the module, not bad user input
271             Carp::confess "array is wrong length, should never happen\n";
272             }
273            
274             if(!$self->_spec()->check_switch($arr[0])) {
275             push(@invalid_args, $arr[0]);
276             if($non_opt_mode eq 'STOP_RET_0') {
277             $self->_set_error("Encountered illegal switch $arr[0]");
278             return 0;
279             } elsif($non_opt_mode eq 'STOP') {
280             last;
281             } elsif($non_opt_mode eq 'SWITCH_RET_0') {
282             $self->_set_error("Encountered illegal switch $arr[0]");
283             return 0;
284             }
285             next;
286             }
287              
288             if($self->_spec()->set_switch($arr[0], $arr[1])) {
289             push(@valid_args, $arr[0]);
290             } else {
291             $self->_set_error($self->_spec()->get_switch_error($arr[0]));
292             return 0;
293             }
294             } elsif(!defined($ret)) {
295             push(@invalid_args, $item);
296             if($non_opt_mode eq 'STOP_RET_0') {
297             $self->_set_error("Encountered illegal switch $item");
298             return 0;
299             } elsif($non_opt_mode eq 'STOP') {
300             last;
301             } elsif($non_opt_mode eq 'SWITCH_RET_0') {
302             $self->_set_error("Encountered illegal switch $item");
303             return 0;
304             }
305             } else { #should never happen
306             my $rt = ref($ret);
307             #this would be an error in the module, not bad user input
308             Carp::confess "returned val $ret of illegal ref type $rt\n"
309             }
310             }
311            
312             #check to see that all required args were set
313             my $argmap = $self->_spec()->_argmap();
314             foreach my $alias (keys %{$argmap}) {
315             if($argmap->{$alias}->required() && !$argmap->{$alias}->is_set()) {
316             my $spec = $argmap->{$alias}->switchspec();
317             $self->_set_error("missing required switch with spec $spec\n");
318             return 0;
319             }
320             }
321            
322             $self->_set_valid_args(\@valid_args);
323             $self->_set_invalid_args(\@invalid_args);
324             $self->_set_extra_args(\@extra_args);
325            
326             return 1;
327             }
328              
329             around 'getopts' => sub {
330             my $orig = shift;
331             my $self = shift;
332            
333             my $ret = $self->$orig();
334            
335             #if using auto_help and help switch given or bad call, show help
336             if($self->_config()->auto_help() && ($self->get_switch('help') || !$ret)) {
337             if(!$ret) {
338             print "**ERROR**: ", $self->get_error(), "\n";
339             }
340             print $self->get_help();
341              
342             if($ENV{'HARNESS_ACTIVE'}) {
343             return $ret;
344             }
345              
346             if(!$ret) {
347             exit(1);
348             } else {
349             exit(0);
350             }
351             }
352              
353             return $ret;
354             };
355              
356             sub _is_switch {
357             my ($self, $switch) = @_;
358            
359             if(!defined($switch)) {
360             return 0;
361             }
362            
363             #does he look like a switch?
364             return $switch =~ /^(-|--)[a-zA-Z?][a-zA-Z0-9=_?-]*/;
365             }
366              
367             sub _parse_switch {
368             my ($self, $switch) = @_;
369            
370             #get the switch type
371             my $switch_type = $self->_switch_type($switch);
372            
373             #no given/when, so use this ugly thing
374             if($switch_type == $_ST_LONG) {
375             return $self->_parse_long_switch($switch);
376             } elsif($switch_type == $_ST_SHORT) {
377             return $self->_parse_short_switch($switch);
378             } elsif($switch_type == $_ST_BUNDLED) {
379             return $self->_parse_bundled_switch($switch);
380             } elsif($switch_type == $_ST_NONE) {
381             return undef;
382             } else {
383             #something is wrong here...
384             Carp::confess "returned illegal switch type $switch_type\n";
385             }
386             }
387              
388             sub _switch_type {
389             my ($self, $switch) = @_;
390            
391             #anything beginning with "--" is a
392             #long switch
393             if($switch =~ /^--/) {
394             return $_ST_LONG;
395             }
396            
397             #could be any kind
398             #single dash, single letter, definitely short
399             if($switch =~ /^-[a-zA-Z_?]$/) {
400             return $_ST_SHORT;
401             }
402            
403             #single dash, single letter, equal sign, definitely short
404             if($switch =~ /^-[a-zA-Z_?]=.+$/) {
405             return $_ST_SHORT;
406             }
407            
408             #short or bundled
409             #already determined it isn't a single letter switch, so check
410             #the non_option_mode to see if it is long
411             if($self->_config()->long_option_mode() eq 'SINGLE_OR_DOUBLE') {
412             return $_ST_LONG;
413             }
414            
415             #could be short, bundled, or none
416             $switch =~ s/^-//;
417             my $c1 = substr($switch, 0, 1);
418             my $c2 = substr($switch, 1, 1);
419            
420             #the first letter doesn't belong to a short switch
421             #so this isn't a valid switch
422             if(!$self->_spec()->check_switch($c1)) {
423             return $_ST_NONE;
424             }
425            
426             #first letter belongs to a switch, but not the second
427             #so this is a short switch of the form "-fboo" where
428             #-f is the switch
429             if($self->_spec()->check_switch($c1) && !$self->_spec()->check_switch($c2)) {
430             return $_ST_SHORT;
431             }
432            
433             #no other choices, it's bundled
434             return $_ST_BUNDLED;
435             }
436              
437             sub _parse_long_switch {
438             my ($self, $switch) = @_;
439            
440             $switch =~ s/^(--|-)//;
441            
442             my @vals = split(/=/, $switch, 2);
443            
444             if($#vals == 0) {
445             return \$vals[0];
446             } else {
447             return [$vals[0], $vals[1]];
448             }
449             }
450              
451             sub _parse_short_switch {
452             my ($self, $switch) = @_;
453            
454             $switch =~ s/^-//;
455            
456             if(length($switch) == 1) {
457             return \$switch;
458             } elsif(index($switch, '=') >= 0) {
459             my @vals = split(/=/, $switch, 2);
460             return {$vals[0] => $vals[1]};
461             } else {
462             return [substr($switch, 0, 1), substr($switch, 1)];
463             }
464             }
465              
466             sub _parse_bundled_switch {
467             my ($self, $switch) = @_;
468            
469             $switch =~ s/^-//;
470            
471             my %rh = ();
472             my %fk = ();
473            
474             my $last_switch;
475             for(my $i = 0; $i < length($switch); ++$i) {
476             my $c = substr($switch, $i, 1);
477            
478            
479             if(defined($fk{$c})) {
480             if(!defined($last_switch)) {
481             #oops, illegal switch
482             #should never get here, make sure switch
483             #is valid and of correct type sooner
484             Carp::confess "illegal switch $switch\n";
485             }
486            
487             #switch appears again in bundle, rest of string is an argument to last switch
488             $rh{$last_switch} = substr($switch, $i);
489             last;
490             } elsif($self->_spec()->check_switch($c)) {
491             $rh{$c} = undef;
492             $fk{$c} = 1;
493             $last_switch = $c;
494             next;
495             } else { #rest of the string was an argument to last switch
496             if(!defined($last_switch)) {
497             #oops, illegal switch
498             #should never get here, make sure switch
499             #is valid and of correct type sooner
500             Carp::confess "illegal switch $switch\n";
501             }
502            
503             if($c eq '=') {
504             $rh{$last_switch} = substr($switch, $i + 1);
505             } else {
506             $rh{$last_switch} = substr($switch, $i);
507             }
508             last;
509             }
510             }
511            
512             #special value so we can pass on
513             #what the last switch was
514             $rh{'~~last'} = $last_switch;
515            
516             return \%rh;
517             }
518              
519              
520             sub add_spec {
521             my ($self, $spec) = @_;
522              
523             my $ospec = $self->spec();
524             my $nspec = merge($spec, $ospec);
525              
526             $self->_set_spec($nspec);
527              
528             $self->_spec(Getopt::Flex::Spec->new({ spec => $self->spec(), config => $self->_config() }));
529              
530             return $nspec;
531             }
532              
533              
534             sub set_args {
535             my ($self, $ref) = @_;
536             return $self->_args(Clone::clone($ref));
537             }
538              
539              
540             sub get_args {
541             my ($self) = @_;
542             return @{Clone::clone($self->_args)};
543             }
544              
545              
546             sub num_valid_args {
547             my ($self) = @_;
548             return $#{$self->valid_args} + 1;
549             }
550              
551              
552             sub get_valid_args {
553             my ($self) = @_;
554             return @{Clone::clone($self->_get_valid_args())};
555             }
556              
557              
558             sub num_invalid_args {
559             my ($self) = @_;
560             return $#{$self->invalid_args} + 1;
561             }
562              
563              
564             sub get_invalid_args {
565             my ($self) = @_;
566             return @{Clone::clone($self->_get_invalid_args())};
567             }
568              
569              
570             sub num_extra_args {
571             my ($self) = @_;
572             return $#{$self->extra_args} + 1;
573             }
574              
575              
576             sub get_extra_args {
577             my ($self) = @_;
578             return @{Clone::clone($self->_get_extra_args())};
579             }
580              
581              
582             sub get_usage {
583             my ($self) = @_;
584            
585             if($self->_config()->usage() eq '') {
586             return "\n";
587             }
588             return 'Usage: '.$self->_config()->usage()."\n";
589             }
590              
591              
592             sub get_help {
593             my ($self) = @_;
594            
595             #find the keys that will give use a unique
596             #set of arguments, using the primary_key
597             #of each argument object
598             my $argmap = $self->_spec()->_argmap();
599             my @primaries = ();
600             foreach my $key (keys %$argmap) {
601             if($argmap->{$key}->primary_name() eq $key && $argmap->{$key}->desc() ne '') {
602             push(@primaries, $key);
603             }
604             }
605            
606             my @help = ();
607            
608             #if we have a usage message, include it
609             if($self->_config()->usage() ne '') {
610             push(@help, 'Usage: ');
611             push(@help, $self->_config()->usage());
612             push(@help, "\n\n");
613             }
614            
615             #if we have a description, include it
616             if($self->_config()->desc() ne '') {
617             push(@help, $self->_config()->desc());
618             push(@help, "\n\n");
619             }
620            
621             #if any of the keys have a description, then...
622             if($#primaries != -1) {
623             #...give us a listing of the options
624             push(@help, "Options:\n\n");
625             foreach my $key (sort @primaries) {
626             if($argmap->{$key}->desc() ne '') {
627             push(@help, $argmap->{$key}->desc());
628             }
629             }
630             }
631            
632             #friends don't let friends end things with two newlines
633             if($help[$#help] =~ /\n\n$/) { pop(@help); push(@help, "\n"); }
634            
635             return join('', @help);
636             }
637              
638              
639             sub get_desc {
640             my ($self) = @_;
641             return $self->_config()->desc()."\n";
642             }
643              
644              
645              
646             sub get_switch {
647             my ($self, $switch) = @_;
648            
649             return $self->_spec()->get_switch($switch);
650             }
651              
652              
653              
654             no Moose;
655              
656             1;
657              
658             __END__
659             =pod
660              
661             =head1 NAME
662              
663             Getopt::Flex - Option parsing, done different.
664              
665             =head1 VERSION
666              
667             version 1.07
668              
669             =head1 SYNOPSIS
670              
671             use Getopt::Flex;
672             my $foo; my $use; my $num; my %has; my @arr;
673            
674             my $cfg = {
675             'non_option_mode' => 'STOP',
676             };
677            
678             my $spec = {
679             'foo|f' => {'var' => \$foo, 'type' => 'Str'},
680             'use|u' => {'var' => \$use, 'type' => 'Bool'},
681             'num|n' => {'var' => \$num, 'type' => 'Num'},
682             'has|h' => {'var' => \%has, 'type' => 'HashRef[Int]'},
683             'arr|a' => {'var' => \@arr, 'type' => 'ArrayRef[Str]'}
684             };
685            
686             my $op = Getopt::Flex->new({spec => $spec, config => $cfg});
687             if(!$op->getopts()) {
688             print "**ERROR**: ", $op->get_error();
689             print $op->get_help();
690             exit(1);
691             }
692              
693             =head1 DESCRIPTION
694              
695             Getopt::Flex makes defining and documenting command line options in
696             your program easy. It has a consistent object-oriented interface.
697             Creating an option specification is declarative and configuration
698             is optional and defaults to a few, smart parameters. Generally,
699             it adheres to the POSIX syntax with GNU extensions for command
700             line options. As a result, options may be longer than a single
701             letter, and may begin with "--". Support also exists for
702             bundling of command line options and using switches without
703             regard to their case, but these are not enabled by defualt.
704              
705             Getopt::Flex is an alternative to other modules in the Getopt::
706             namespace, including the much used L<Getopt::Long> and
707             L<Getopt::Long::Descriptive>. Other options include L<App::Cmd>
708             and L<MooseX::Getopt> (which actually sit on top of L<Getopt::Long::Descriptive>).
709             If you don't like this solution, try one of those.
710              
711             =head1 Getting started with Getopt::Flex
712              
713             Getopt::Flex supports long and single character options. Any character
714             from [a-zA-Z0-9_?-] may be used when specifying an option. Options
715             must not end in -, nor may they contain two consecutive dashes.
716              
717             To use Getopt::Flex in your Perl program, it must contain the following
718             line:
719              
720             use Getopt::Flex;
721              
722             In the default configuration, bundling is not enabled, long options
723             must start with "--" and non-options may be placed between options.
724              
725             Then, create a configuration, if necassary, like so:
726              
727             my $cfg = { 'non_option_mode' => 'STOP' };
728              
729             For more information about configuration, see L<Configuring Getopt::Flex>.
730             Then, create a specification, like so:
731              
732             my $spec = {
733             'foo|f' => {'var' => \$foo, 'type' => 'Str'},
734             };
735              
736             For more information about specifications, see L<Specifying Options to Getopt::Flex>. Create
737             a new Getopt::Flex object:
738              
739             my $op = Getopt::Flex->new({spec => $spec, config => $cfg});
740              
741             And finally invoke the option processor with:
742              
743             $op->getopts();
744              
745             Getopt::Flex automatically uses the global @ARGV array for options.
746             If you would like to supply your own, you may use C<set_args()>, like this:
747              
748             $op->set_args(\@args);
749              
750             In the event of an error, C<getopts()> will return false,
751             and set an error message which can be retrieved via C<get_error()>.
752              
753             Getopt::Flex also stores information about valid options, invalid options
754             and extra options. Valid options are those which Getopt::Flex recognized
755             as valid, and invalid are those that were not. Anything that is not an
756             option can be found in extra options. These values can be retrieved via:
757              
758             my @va = $op->get_valid_args();
759             my @ia = $op->get_invalid_args();
760             my @ea = $op->get_extra_args();
761              
762             Getopt::Flex may also be used to provide an automatically formatted help
763             message. By setting the appropriate I<desc> when specifying an option,
764             and by setting I<usage> and I<desc> in the configuration, a full help
765             message can be provided, and is available via:
766              
767             my $help = $op->get_help();
768              
769             Usage and description are also available, via:
770              
771             my $usage = $op->get_usage();
772             my $desc = $op->get_desc();
773              
774             An automatically generated help message would look like this:
775              
776             Usage: foo [OPTIONS...] [FILES...]
777            
778             Use this to manage your foo files
779            
780             Options:
781            
782             --alpha, --beta, Pass any greek letters to this argument
783             --delta, --eta, --gamma
784             -b, --bar When set, indicates to use bar
785             -f, --foo Expects a string naming the foo
786              
787             =head1 Specifying Options to Getopt::Flex
788              
789             Options are specified by way of a hash whose keys define valid option
790             forms and whose values are hashes which contain information about the
791             options. For instance,
792              
793             my $spec = {
794             'file|f' => {
795             'var' => \$file,
796             'type' => 'Str'
797             }
798             };
799              
800             Defines a switch called I<file> with an alias I<f> which will set variable
801             C<$var> with a value when encountered during processing. I<type> specifies
802             the type that the input must conform to. Only I<type> is required
803             when specifying an option. If no I<var> is supplied, you may still access
804             that switch through the C<get_switch> method. It is recommended that you do
805             provide a I<var>, however. For more information about C<get_switch> see
806             L<get_switch>. In general, options must conform to the following:
807              
808             $_ =~ m/^[a-zA-Z0-9|_?-]+$/ && $_ =~ m/^[a-zA-Z_?]/ && $_ !~ m/\|\|/ && $_ !~ /--/ && $_ !~ /-$/
809              
810             Which (in plain english) means that you can use any letter A through Z, upper- or lower-case,
811             any number, underscores, dashes, and question marks. The pipe symbol is used to separate the
812             various aliases for the switch, and must not appear together (which would produce an empty
813             switch). No switch may contain two consecutive dashes, and must not end with a dash. A switch
814             must also begin with A through Z, upper- or lower-case, an underscore, or a question mark.
815              
816             The following is an example of all possible arguments to an option specification:
817              
818             my $spec = {
819             'file|f' => {
820             'var' => \$file,
821             'type' => 'Str',
822             'desc' => 'The file to process',
823             'required' => 1,
824             'validator' => sub { $_[0] =~ /\.txt$/ },
825             'callback' => sub { print "File found\n" },
826             'default' => 'input.txt',
827             }
828             };
829              
830             Additional specifications may be added by calling C<add_spec>. This allows
831             one to dynamically build up a set of valid options.
832              
833             =head2 Specifying a var
834              
835             When specifying a I<var>, you must provide a reference to the variable,
836             and not the variable itself. So C<\$file> is ok, while C<$file> is not.
837             You may also pass in an array reference or a hash reference, please see
838             L<Specifying a type> for more information.
839              
840             Specifying a I<var> is optional, as discussed above.
841              
842             =head2 Specifying a type
843              
844             A valid type is any type that is "simple" or an ArrayRef or HashRef parameterized
845             with a simple type. A simple type is one that is a subtype of C<Bool>, C<Str>,
846             C<Num>, or C<Int>.
847              
848             Commonly used types would be the following:
849              
850             Bool Str Num Int ArrayRef[Str] ArrayRef[Num] ArrayRef[Int] HashRef[Str] HashRef[Num] HashRef[Int] Inc
851              
852             The type C<Inc> is an incremental type (actually simply an alias for Moose's C<Int> type),
853             whose value will be increased by one each time
854             its appropriate switch is encountered on the command line. When using an C<ArrayRef>
855             type, the supplied var must be an array reference, like C<\@arr> and NOT C<@arr>.
856             Likewise, when using a C<HashRef> type, the supplied var must be a hash reference,
857             e.g. C<\%hash> and NOT C<%hash>.
858              
859             You can define your own types as well. For this, you will need to import C<Moose> and
860             C<Moose::Util::TypeConstraints>, like so:
861              
862             use Moose;
863             use Moose::Util::TypeConstraints;
864              
865             Then, simply use C<subtype> to create a subtype of your liking:
866              
867             subtype 'Natural'
868             => as 'Int'
869             => where { $_ > 0 };
870              
871             This will automatically register the type for you and make it visible to Getopt::Flex.
872             As noted above, those types must be a subtype of C<Bool>, C<Str>, C<Num>, or C<Int>.
873             Any other types will cause Getopt::Flex to signal an error. You may use these subtypes
874             that you define as parameters for the ArrayRef or Hashref parameterizable types, like so:
875              
876             my $sp = { 'foo|f' => { 'var' => \@arr, 'type' => 'ArrayRef[Natural]' } };
877              
878             or
879              
880             my $sp = { 'foo|f' => { 'var' => \%has, 'type' => 'HashRef[Natural]' } };
881              
882             For more information about types and defining your own types, see L<Moose::Manual::Types>.
883              
884             Specifying a I<type> is required.
885              
886             =head2 Specifying a desc
887              
888             I<desc> is used to provide a description for an option. It can be used
889             to provide an autogenerated help message for that switch. If left empty,
890             no information about that switch will be displayed in the help output.
891             See L<Getting started with Getopt::Flex> for more information.
892              
893             Specifying a I<desc> is optional, and defaults to ''.
894              
895             =head2 Specifying required
896              
897             Setting I<required> to a true value will cause it make that value required
898             during option processing, and if it is not found will cause an error condition.
899              
900             Specifying I<required> is not required, and defaults to 0.
901              
902             =head2 Specifying a validator
903              
904             A I<validator> is a function that takes a single argument and returns a boolean
905             value. Getopt::Flex will call the validator function when the option is
906             encountered on the command line and pass to it the value it finds. If the value
907             does not pass the supplied validation check, an error condition is caused.
908              
909             Specifying a I<validator> is not required.
910              
911             =head2 Specifying a callback
912              
913             A I<callback> is a function that takes a single argument which Getopt::Flex will
914             then call when the option is encountered on the command line, passing to it the value it finds.
915              
916             Specifying a I<callback> is not required.
917              
918             =head2 Specifying a default
919              
920             I<default>s come in two flavors, raw values and subroutine references.
921             For instance, one may specify a string as a default value, or a subroutine
922             which returns a string:
923              
924             'default' => 'some string'
925              
926             or
927              
928             'default' => sub { return "\n" }
929              
930             When specifying a default for an array or hash, it is necessary to use
931             a subroutine to return the reference like,
932              
933             'default' => sub { {} }
934              
935             or
936              
937             'default' => sub { [] }
938              
939             This is due to the way Perl handles such syntax. Additionally, defaults
940             must be valid in relation to the specified type and any specified
941             validator function. If not, an error condition is signalled.
942              
943             Specifying a I<default> is not required.
944              
945             =head1 Configuring Getopt::Flex
946              
947             Configuration of Getopt::Flex is very simple. Such a configuration
948             is specified by a hash whose keys are the names of configuration
949             option, and whose values indicate the configuration. Below is a
950             configuration with all possible options:
951              
952             my $cfg = {
953             'non_option_mode' => 'STOP',
954             'bundling' => 0,
955             'long_option_mode' => 'SINGLE_OR_DOUBLE',
956             'case_mode' => 'INSENSITIVE',
957             'usage' => 'foo [OPTIONS...] [FILES...]',
958             'desc' => 'Use foo to manage your foo archives',
959             'auto_help' => 1,
960             };
961              
962             What follows is a discussion of each option.
963              
964             =head2 Configuring non_option_mode
965              
966             I<non_option_mode> tells the parser what to do when it encounters anything
967             which is not a valid option to the program. Possible values are as follows:
968              
969             STOP IGNORE SWITCH_RET_0 VALUE_RET_0 STOP_RET_0
970              
971             C<STOP> indicates that upon encountering something that isn't an option, stop
972             processing immediately. C<IGNORE> is the opposite, ignoring everything that
973             isn't an option. The values ending in C<_RET_0> indicate that the program
974             should return immediately (with value 0 for false) to indicate that there was a
975             processing error. C<SWITCH_RET_0> means that false should be returned in the
976             event an illegal switch is encountered. C<VALUE_RET_0> means that upon
977             encountering a value, the program should return immediately with false. This
978             would be useful if your program expects no other input other than option
979             switches. C<STOP_RET_0> means that if an illegal switch or any value is
980             encountered that false should be returned immediately.
981              
982             The default value is C<IGNORE>.
983              
984             =head2 Configuring bundling
985              
986             I<bundling> is a boolean indicating whether or not bundled switches may be used.
987             A bundled switch is something of the form:
988              
989             -laR
990              
991             Where equivalent unbundled representation is:
992              
993             -l -a -R
994              
995             By turning I<bundling> on, I<long_option_mode> will automatically be set to
996             C<REQUIRE_DOUBLE_DASH>.
997              
998             Warning: If you pass an illegal switch into a bundle, it may happen that the
999             entire bundle is treated as invalid, or at least several of its switches.
1000             For this reason, it is recommended that you set I<non_option_mode> to
1001             C<SWITCH_RET_0> when bundling is turned on. See L<Configuring non_option_mode>
1002             for more information.
1003              
1004             The default value is C<0>.
1005              
1006             =head2 Configuring long_option_mode
1007              
1008             This indicates what long options should look like. It may assume the
1009             following values:
1010              
1011             REQUIRE_DOUBLE_DASH SINGLE_OR_DOUBLE
1012              
1013             C<REQUIRE_DOUBLE_DASH> is the default. Therefore, by default, options
1014             that look like:
1015              
1016             --verbose
1017              
1018             Will be treated as valid, and:
1019              
1020             -verbose
1021              
1022             Will be treated as invalid. Setting I<long_option_mode> to C<SINGLE_OR_DOUBLE>
1023             would make the second example valid as well. Attempting to set I<bundling> to
1024             C<1> and I<long_option_mode> to C<SINGLE_OR_DOUBLE> will signal an error.
1025              
1026             The default value is C<REQUIRE_DOUBLE_DASH>.
1027              
1028             =head2 Configuring case_mode
1029              
1030             I<case_mode> allows you to specify whether or not options are allowed to be
1031             entered in any case. The following values are valid:
1032              
1033             SENSITIVE INSENSITIVE
1034              
1035             If you set I<case_mode> to C<INSENSITIVE>, then switches will be matched without
1036             regard to case. For instance, C<--foo>, C<--FOO>, C<--FoO>, etc. all represent
1037             the same switch when case insensitive matching is turned on.
1038              
1039             The default value is C<SENSITIVE>.
1040              
1041             =head2 Configuring usage
1042              
1043             I<usage> may be set with a string indicating appropriate usage of the program.
1044             It will be used to provide help automatically.
1045              
1046             The default value is the empty string.
1047              
1048             =head2 Configuring desc
1049              
1050             I<desc> may be set with a string describing the program. It will be used when
1051             providing help automatically.
1052              
1053             The default value is the empty string.
1054              
1055             =head2 Configuring auto_help
1056              
1057             I<auto_help> can be set to true to enable the automatic creation of a C<help|h>
1058             switch, which, when detected, will cause the help to be printed and exit(0) to
1059             be called. Additionally, if the given switches are illegal (according to your
1060             configuration and spec), the error will be printed, the help will be printed,
1061             and exit(1) will be called.
1062              
1063             Use of auto_help also means you may not define other switches C<help> or C<h>.
1064              
1065             The default value is false.
1066              
1067             =head1 METHODS
1068              
1069             =head2 getopts
1070              
1071             Invoking this method will cause the module to parse its current arguments array,
1072             and apply any values found to the appropriate matched references provided.
1073              
1074             =head2 add_spec
1075              
1076             Add an additional spec to the current spec.
1077              
1078             =head2 set_args
1079              
1080             Set the array of args to be parsed. Expects an array reference.
1081              
1082             =head2 get_args
1083              
1084             Get the array of args to be parsed.
1085              
1086             =head2 num_valid_args
1087              
1088             After parsing, this returns the number of valid switches passed to the script.
1089              
1090             =head2 get_valid_args
1091              
1092             After parsing, this returns the valid arguments passed to the script.
1093              
1094             =head2 num_invalid_args
1095              
1096             After parsing, this returns the number of invalid switches passed to the script.
1097              
1098             =head2 get_invalid_args
1099              
1100             After parsing, this returns the invalid arguments passed to the script.
1101              
1102             =head2 num_extra_args
1103              
1104             After parsing, this returns anything that wasn't matched to a switch, or that was not a switch at all.
1105              
1106             =head2 get_extra_args
1107              
1108             After parsing, this returns the extra parameter passed to the script.
1109              
1110             =head2 get_usage
1111              
1112             Returns the supplied usage message, or a single newline if none given.
1113              
1114             =head2 get_help
1115              
1116             Returns an automatically generated help message
1117              
1118             =head2 get_desc
1119              
1120             Returns the supplied description, or a single newline if none provided.
1121              
1122             =head2 get_error
1123              
1124             Returns an error message if set, empty string otherwise.
1125              
1126             =head2 get_switch
1127              
1128             Passing this function the name of a switch (or the switch spec) will
1129             cause it to return the value of a ScalarRef, a HashRef, or an ArrayRef
1130             (based on the type given), or undef if the given switch does not
1131             correspond to any defined switch.
1132              
1133             =for Pod::Coverage BUILD
1134              
1135             =head1 REPOSITORY
1136              
1137             The source code repository for this project is located at:
1138              
1139             http://github.com/f0rk/getopt-flex
1140              
1141             =head1 AUTHOR
1142              
1143             Ryan P. Kelly <rpkelly@cpan.org>
1144              
1145             =head1 COPYRIGHT AND LICENSE
1146              
1147             This software is Copyright (c) 2011 by Ryan P. Kelly.
1148              
1149             This is free software, licensed under:
1150              
1151             The MIT (X11) License
1152              
1153             =cut
1154