コマンドラインオプションを解析するPerlモジュールGetopt::Compact
Perlでコマンドラインオプションを解析する場合、大体は標準添付されているGetopt::Longを使うと思いますが、自分は3年前ぐらいから Getopt::Compact というモジュールに出会い、それ以降大抵の場合はこれを使っています。このモジュールの良いところは
- オプションの定義(-c, –config などの定義)とそのヘルプメッセージが一箇所で定義できる
- -h, –helpオプションを最初から定義してくれてる(–manオプションも)
- 定義してないオプションが指定されると自動的にエラーにしてくれる
- Getopt::Compact#usage でヘルプメッセージが簡単に取得できる
があると思っています。などと抽象的な話をしてもしょうがないので、具体的なコードを書いてみます。
#!/usr/bin/env perl use strict; use warnings; use Getopt::Compact; use Data::Dumper; my $getopt = Getopt::Compact->new( name => 'getopt_compact.pl', modes => [ qw(verbose) ], args => 'FILE', version => '0.1', struct => [ [ [ qw(f force) ], 'force overwrite of output file and compress links' ], [ [ qw(l level) ], 'compress level', '=i' ], [ [ qw(S suffix) ], 'use suffix on compressed files', '=s' ], ] ); my $options = $getopt->opts; my $file = shift @ARGV; unless ($file) { print STDERR $getopt->usage; exit 1; } print "options -----\n"; print Dumper $options;
上の例では gzip のオプションのモノマネで
- -f, –forceというフラグオプション
- -l, –levelという数値のオプション
- -S, –suffixという文字列のオプション
- オプション以外に引数FILEを受け取る
という仕様としています。
でで、例えば
$ perl getopt_compact.pl --help
と実行すると
getopt_compact.pl v0.1 usage: getopt_compact.pl [options] FILE options -h, --help This help message -v, --verbose Verbose mode -f, --force Force overwrite of output file and compress links -l, --level Compress level -S, --suffix Use suffix on compressed files --man Display documentation
のようにヘルプが表示されます。また、–hoge のような存在しないオプションを指定すると
$ perl getopt_compact.pl --hoge Unknown option: hoge getopt_compact.pl v0.1 usage: getopt_compact.pl [options] FILE options -h, --help This help message -v, --verbose Verbose mode -f, --force Force overwrite of output file and compress links -l, --level Compress level -S, --suffix Use suffix on compressed files --man Display documentation
のようにエラーになりヘルプが表示されます。
という感じで、Getopt::Longより依存モジュールがあるものの便利に使わせてもらってます。ただ、PerlのGetopt系のモジュールは他にも色々あるのでもっと便利なのがありそうですが、こういうのもあるよという紹介でした。
こちらもあわせてどうぞ

コメント