#amazon(4797336803)
#amazon(4873115671)
概要 †
- getopt
- オプションと引数を受け取る
- 各オプションには必ず引数が必要
- ただし、getopt で定義しなければオプションのみを受け取ることが可能
- getopts
- オプションを受け取る
- 定義次第で引数を受け取ることも可能
- オプションのみの場合、引数の代わりに 1 が入る
getopt †
書式 †
- オプションの定義
getopt "opt[opt2...]";
- opt
- オプション、一つのオプションにつきアルファベット 1 文字
- 引数の使用
print "$opt_opt";
実行方法 †
使用例 †
- ex) 引数を複数受け取る場合
host# cat sample.pl
#!/usr/bin/perl
use strict;
use Getopt::Std;
our ($opt_a, $opt_b, $opt_c);
getopt "abc";
if ($opt_a) {
print "a argument is $opt_a.\n";
} else {
print "a argument is not set.\n";
}
if ($opt_b) {
print "b argument is $opt_b.\n";
} else {
print "b argument is not set.\n";
}
if ($opt_c) {
print "c argument is $opt_c.\n";
} else {
print "c argument is not set.\n";
}
host# ./sample.pl -a value1 -b value2 -c value3
a argument is value1.
b argument is value2.
c argument is value3.
host# ./sample.pl -a value1 -b value2
a argument is value1.
b argument is value2.
c argument is not set.
host# ./sample.pl
a argument is not set.
b argument is not set.
c argument is not set.
getopts †
書式 †
- オプションの定義
getopts "opt[:]";
- opt
- オプション、一つのオプションにつきアルファベット 1 文字
- : (Colon) を付けると引数を受け取ることが出来る
- 引数の使用
print "$opt_opt";
- $opt_opt
- 引数が代入される変数
- オプションのみの場合で指定された場合は 1 が入る
ハッシュ関数の利用 †
- $opt_opt 変数ではなく、ハッシュ変数を使用することも出来る
getopts("opt", \%arg);
- 引数の使用
print "$opt{arg}";
実行方法 †
使用例 †
- ex) 複数のオプションを指定し、オプション a のみ引数を受け取る場合
host# cat sample.pl
#!/usr/bin/perl
use strict;
use Getopt::Std;
our ($opt_a, $opt_b, $opt_c);
getopts "a:bc";
if ($opt_a) {
print "a argument is $opt_a.\n";
} else {
print "a option is not set.\n";
}
if ($opt_b) {
print "b argument is $opt_b.\n";
} else {
print "b option is not set.\n";
}
if ($opt_c) {
print "c argument is $opt_c.\n";
} else {
print "c option is not set.\n";
}
host# ./sample.pl -a aaa -b -c
a argument is aaa.
b argument is 1.
c argument is 1.
host# ./sample.pl -a aaa -b
a argument is aaa.
b argument is 1.
c option is not set.
host# ./sample.pl -a
a option is not set.
b option is not set.
c option is not set.