Last active
August 29, 2015 14:02
-
-
Save s-shin/078c98782100de894f8f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package Cmdline; | |
| use strict; | |
| use warnings; | |
| use Getopt::Long; | |
| use Pod::Usage; | |
| use Carp; | |
| use parent qw(Exporter); | |
| our @EXPORT = qw(cmdline); | |
| sub cmdline { | |
| my $cmd_opts = @_ == 1 ? $_[0] : \%{@_}; | |
| my %opts; | |
| my @formats; | |
| my @required_opts; | |
| while (my ($name, $definition) = each(%$cmd_opts)) { | |
| $opts{$name} = $definition->{default} || undef; | |
| push @formats, $name . $definition->{format}; | |
| push @required_opts, $name if $definition->{required}; | |
| } | |
| # parse command line | |
| my $parser = Getopt::Long::Parser->new( | |
| config => [qw(bundling no_ignore_case auto_help)], | |
| ); | |
| pod2usage(1) unless $parser->getoptions(\%opts, @formats); | |
| # check required | |
| foreach my $name (@required_opts) { | |
| unless (defined($opts{$name})) { | |
| print STDERR "Option '${name}' is required.\n"; | |
| pod2usage(1); | |
| } | |
| } | |
| \%opts; | |
| } | |
| __END__ | |
| =head1 NAME | |
| Cmdline - Very simple wrapper of Getopt::Long | |
| =head1 SYNOPSYS | |
| use Cmdline; | |
| my $opts = cmdline { | |
| input => { | |
| format => '|i=s', | |
| required => 1, | |
| default => 'input.txt' | |
| }, | |
| output => { | |
| format => '|o=s', | |
| }, | |
| }; | |
| __END__ | |
| =head1 OPTIONS | |
| =over 4 | |
| =item --input|-i STRING (default: 'input.txt') | |
| =item --output|-o STRING | |
| =back | |
| =head1 AUTHOR | |
| Shintaro Seki <[email protected]> | |
| =head1 SEE ALSO | |
| L<Getopt::Long> | |
| =head1 LICENSE | |
| (C) Shintaro Seki | |
| This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | |
| =cut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment