2013年もGetopt::Long(中編)
という訳で、前回の続き。
ハッシュで受け取るとか、必須項目とデフォルト値の対応とか。
参考にしたページ
2013年のGetopt::Long – おそらくはそれさえも平凡な日々
http://www.songmu.jp/riji/archives/2013/02/2013getoptlong.html
ハッシュで受け取る
use strict;
use warnings;
use v5.10;
use Getopt::Long qw/:config posix_default no_ignore_case bundling auto_help/;
my $res = GetOptions(
\my %opt,
'hoge'
);
say 'hoge = ', $opt{hoge};
say 'res = ', $res;
上記のソースを”eee.pl”に保存して、
以下のように実行すると、
$ perl eee.pl
Use of uninitialized value in say at eee.pl line 12.
hoge =
res = 1
これだと、値が入るので警告がでない。
$ perl eee.pl --hoge
hoge = 1
res = 1
引数を受け取るには、'hoge'を'hoge=s'に変更して、
“fff.pl”に保存して実行する。
$ perl fff.pl --hoge
Option hoge requires an argument
Use of uninitialized value in say at fff.pl line 12.
hoge =
res =
この場合、こういうのを想定している。
$ perl fff.pl --hoge aaa
hoge = aaa
res = 1
こっちでも、もちろんOK。
$ perl fff.pl --hoge=aaa
hoge = aaa
res = 1
必須項目とデフォルト値
たとえば、--hogeには何か指定しないとダメだけど、
--fooと--barはあってもなくても良い場合。
use strict;
use warnings;
use v5.10;
use Getopt::Long qw/:config posix_default no_ignore_case bundling auto_help/;
my $res = GetOptions(
\my %opt,
'hoge=s',
'foo=s',
'bar=i'
);
die '--hoge is required.' if ( not exists $opt{hoge} );
say 'hoge = ', $opt{hoge};
say 'foo = ', $opt{foo};
say 'bar = ', $opt{bar};
say 'res = ', $res;
上記のソースを”fff.pl”に保存して、
以下のように実行すると、
$ cp fff.pl ggg.pl
nekoair:getopt nekoair$ perl ggg.pl
--hoge is required. at ggg.pl line 14.
もちろん、これもダメ。
$ perl ggg.pl --hoge
Option hoge requires an argument
--hoge is required. at ggg.pl line 14.
引数を指定すれば、ちゃんと動く。
$ perl ggg.pl --hoge aaa
hoge = aaa
Use of uninitialized value in say at ggg.pl line 17.
foo =
Use of uninitialized value in say at ggg.pl line 18.
bar =
res = 1
次に、--fooと--barをデフォルト値で動作させたいので、
以下のように編集する。
use strict;
use warnings;
use v5.10;
use Getopt::Long qw/:config posix_default no_ignore_case bundling auto_help/;
my %opt = (
foo => 'bbb',
bar => 2
);
my $res = GetOptions(
\%opt,
'hoge=s',
'foo=s',
'bar=i'
);
die '--hoge is required.' if ( not exists $opt{hoge} );
say 'hoge = ', $opt{hoge};
say 'foo = ', $opt{foo};
say 'bar = ', $opt{bar};
say 'res = ', $res;
これを、”hhh.pl”に保存して、
以下のように実行すると、
$ perl hhh.pl --hoge aaa
hoge = aaa
foo = bbb
bar = 2
res = 1
もしくは、必須項目のチェックと同じ要領でデフォルト値を入れても良いと思う。
ちなみに、デフォルト値を上書きする場合はこんな感じ。
$ perl hhh.pl --hoge aaa --foo ccc
hoge = aaa
foo = ccc
bar = 2
res = 1
$ perl hhh.pl --hoge aaa --bar 3
hoge = aaa
foo = bbb
bar = 3
res = 1
続く。
Leave a Comment