perl学习笔记05_命令行选项

1. Getopt::Long

#使用模块
use Getopt::Long ;

#选项初始值
my $length = 24 ;
my $file = "file.dat";
my @run = ();
my $verbose =0;

#处理选项
# 如果参数解析成功, $result=1,
# 如果参数解析失败(有未知选项或不符合要求), $result=0
my $result = GetOptions(
    "length=i"  => \$length    , # i表示integer, 整型选项
    "file=s"    => \$file      , # s表示string, 字符串选项
    "run=s{1,}" => \@run , # {1,}表示数组, 至少一个元素
    "verbose|?" => \$verbose   , # flag, |?表示长度可变, 命令行有此选项, 则$verbose=1
);

print("length   = $length\n");
print("file     = $file\n");
print("run      = @run\n");
print("verbose  = $verbose\n");

执行

$ ex.pl -file a.txt -run a.run b.run -v
length   = 24           # 命令行没指定, 是默认值
file     = a.txt        # 命令行指定为 a.txt
run      = a.run b.run  # 命令行指定为 a.run b.run
verbose  = 1            # 命令行指定, 值为1

2. Getopt::Std

use Getopt::Std; # 用于选项都是一个字符的情况

my %opt;

# 三个选项,
#   d和f后面有冒号, 表示选项有参数,
#   o后面没冒号, 表示是个flag.
getopts("d:f:o", \%opt);

print "\$opt{d} => $opt{d}\n" if $opt{d};
print "\$opt{f} => $opt{f}\n" if $opt{f};
print "\$opt{o} => $opt{o}\n" if $opt{o};

执行:

$ ex.pl -d 2013 -f file.dat -o
$opt{d} => 2013
$opt{f} => file.dat
$opt{o} => 1
posted @ 2023-07-15 17:27  编程驴子  阅读(12)  评论(0编辑  收藏  举报