#!/usr/bin/perl
#
# getopt-cmd-template.pl
#
use Text::ParseWords ;
sub usage_exit {
print STDERR "Usage: getopt-cmd-template.pl [-a] [-d dir] item1 item2 ...\n" ;
exit 1 ;
}
sub get_quotedwordstr {
my $s ;
foreach (@_) {
$s = sprintf("$s '%s'", "$_") ;
}
return $s ;
}
print "@ARGV\n" ; ####DEBUG
$argstr = get_quotedwordstr(@ARGV) ;
print "$argstr\n" ; ####DEBUG
$optstr = `getopt -q -o ad:h -- $argstr` ; if ($? != 0) { usage_exit ; }
@opts = shellwords($optstr) ;
while (1) {
$_ = shift @opts ;
m/^$/ && do { next ; } ;
m/^-a/ && do { $opt_a = 1 ; next ; } ;
m/^-d/ && do { $opt_d = shift @opts ; next ; } ;
m/^--/ && do { last ; } ;
usage_exit ;
}
$argc = scalar @opts ;
print "\$argc=$argc\n" ; ####DEBUG
print "\@opts=@opts\n" ; ####DEBUG
print "\$opt_a=$opt_a\n" ; ####DEBUG
print "\$opt_d=$opt_d\n" ; ####DEBUG
ひと手間かかった部分だけ補足しますと、空白を含むような item にも対応できるように、get_quotedwordstr を記述しています。
また、getopt(1) の処理結果をうまく単語分割して配列に格納するため、Text::ParseWords に含まれる shellwords を使いました。これの存在に気づくまで時間がかかりました。
実行結果は、次のようになります。
# ./getopt-cmd-template.pl -d dir item1 item2 -d dir item1 item2 '-d' 'dir' 'item1' 'item2' $argc=2 @opts=item1 item2 $opt_a= $opt_d=dirコマンドラインの後半でオプション指定しても、うまく処理されます。
# ./getopt-cmd-template.pl item1 item2 -d dir item1 item2 -d dir 'item1' 'item2' '-d' 'dir' $argc=2 @opts=item1 item2 $opt_a= $opt_d=dirGetopt::Std では、このように、うまく処理はできません。次の記事を参照ください。
perl でオプション解析(Getopt::Std編)
0 件のコメント:
コメントを投稿