diff options
author | Kent Fredric <kentfredric@gmail.com> | 2012-02-29 10:44:07 +1300 |
---|---|---|
committer | Kent Fredric <kentfredric@gmail.com> | 2012-02-29 10:44:07 +1300 |
commit | 723c2e4563ab8e24e219bfce8f371f73d0f26513 (patch) | |
tree | c5fedf689ff960ca18d478f1b4e49a88bccf50e0 /scripts/lib | |
parent | [scripts/lib/deptools.pm] Add a few more exceptions ( perltidy ) (diff) | |
download | perl-overlay-723c2e4563ab8e24e219bfce8f371f73d0f26513.tar.gz perl-overlay-723c2e4563ab8e24e219bfce8f371f73d0f26513.tar.bz2 perl-overlay-723c2e4563ab8e24e219bfce8f371f73d0f26513.zip |
[scripts] factor out my simple option parsing logic to a lib
Diffstat (limited to 'scripts/lib')
-rw-r--r-- | scripts/lib/optparse.pm | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/scripts/lib/optparse.pm b/scripts/lib/optparse.pm new file mode 100644 index 000000000..296184b7b --- /dev/null +++ b/scripts/lib/optparse.pm @@ -0,0 +1,62 @@ +use strict; +use warnings; + +package optparse; + +# FILENAME: optparse.pm +# CREATED: 29/02/12 07:50:47 by Kent Fredric (kentnl) <kentfredric@gmail.com> +# ABSTRACT: Lightweight option parser; + +use Moose; + +has 'help' => ( isa => 'CodeRef', is => 'rw', required => 1 ); +has 'argv' => ( isa => 'ArrayRef', is => 'rw', required => 1 ); + +has 'long_opts' => ( isa => 'HashRef', is => 'rw', 'lazy_build' => 1 ); +has 'opts' => ( isa => 'HashRef', is => 'rw', lazy_build => 1 ); +has 'extra_opts' => ( isa => 'ArrayRef', is => 'rw', 'lazy_build' => 1 ); + +sub _build_extra_opts { + my $self = shift; + return [ grep { $_ !~ /^--(.+)/ and $_ !~ /^-(\w+)/ } @{ $self->argv } ]; +} + +sub _build_opts { + my $self = shift; + my $hash = {}; + for my $arg ( @{ $self->argv } ) { + next if $arg =~ /^--(.+)/; + next unless $arg =~ /^-(\w+)/; + $hash->{$1}++; + } + return $hash; +} + +sub _build_long_opts { + my $self = shift; + my $hash = {}; + for my $arg ( @{ $self->argv } ) { + next unless $arg =~ /^--(.+)/; + my ($token) = "$1"; + if ( $token =~ /^([^=]+)=(.*$)/ ) { + $hash->{$1} = $2; + } + else { + $hash->{$token}++; + } + } + return $hash; +} + +sub BUILD { + my ($self) = shift; + if ( defined $self->opts->{h} or defined $self->long_opts->{help} ) { + $self->help->(); + exit 0; + } +} + +no Moose; +__PACKAGE__->meta->make_immutable; +1; + |