今回は、コマンドラインの引数受け取りに役立つ Getopt::Long と Pod::Usage の使い方を簡単にまとめます。
Getopt::Long と Pod::Usage にはたくさんのオプションがありますが、私の場合、次のように使用しています。
#!/usr/local/bin/perl use strict; use warnings; use Getopt::Long qw(:config auto_help); #--helpや-h、-?で自動的にhelp表示 use Pod::Usage; use Data::Dumper; #受け取るoptionの定義 #s=文字列型, i=整数型, f=実数型, @=同optionを複数回指定可, 型なし=boolean my @OPTIONS_DEF = qw/class=s@ id=s before=i help/; #optionのdefault値 my $OPTIONS = {before => 1,class=>[]}; sub main { print STDERR Dumper(\@ARGV); #optionの受け取り. 失敗した場合、helpを表示 GetOptions($OPTIONS, @OPTIONS_DEF) or pod2usage(-verbose => 2); pod2usage(-verbose => 2) if $OPTIONS->{help}; print STDERR Dumper($OPTIONS); #GetOptionsで取得された残りの@ARGVが表示されます print STDERR Dumper(\@ARGV); return 1; } main(); exit; __END__ =head1 NAME Getopt::Long Pod::Usage test =head1 SYNOPSIS trend.pl [options] Options: --class test class --all test all class --before test from ? days before --help put help message cut
初めにcpanにあるドキュメントを読まなかったので、
pod2usage()の使い方をちょっと迷いましたが、読めば納得。
http://search.cpan.org/~marekr/Pod-Parser-1.35/lib/Pod/Usage.pm
- verbose
The desired level of "verboseness" to use when printing the usage message. If the corresponding value is 0, then only the "SYNOPSIS" section of the pod documentation is printed. If the corresponding value is 1, then the "SYNOPSIS" section, along with any section entitled "OPTIONS", "ARGUMENTS", or "OPTIONS AND ARGUMENTS" is printed. If the corresponding value is 2 or more then the entire manpage is printed.