您的位置:首页 > 运维架构

[Perl] 利用Geopt::Long模块接收命令行参数

2015-03-02 15:03 295 查看
当perl程序需要处理用户输入的参数时,有两种方式:

第一种方法是:使用@ARGV数组

第二种方法是:调用Getopt::Long模块,该方法方便而强大。本文主要介绍该方法。

Getopt::Long 在Perl中的调用实例:

#!/usr/bin/perl
use Getopt::Long;
my ($verbose, $monitor, $debug, $test);
my @libs = ();
my %flags = ();

GetOptions (
  'verbose+' => \$verbose,
  'monitor!'   => \$monitor,
  'debug:i'    => \$debug,
  'test|t=s'   => \$test,
  'lib=s'      => \$@libs,
'flag=s'     => \%flags,
);

print "verbose=$verbose, monitor=$monitor, debug=$debug, test=$test, libs=@libs\n";
while (my($k, $v)=each%flags) {
print "$k=>$v\n";
}


代码解释:

1. ‘verbose+’ :“+”表示不需要在该选项后跟参数,每使用一次该选项会verbose变量自动加1.

如:在命令行中出现 -verbose -verbose 2次,verbose的值变为2.

2. ‘monitor!’ : “!”表示该选项不需要后跟参数,直接使用即可(-monitor)。此时more的默认值为1.

常用于设置打开和关闭一个功能,-monitor表示打开,-nomonitor表示关闭。

3. ‘debug:i’ : “:”表示该选项后跟的参数可以是0或空字符

4. ‘test|t=s’ : "|" 表示该选项可以简写,如-test可以简写为-t

“=” 表示该选项必须跟参数

5. ‘lib=s’ => \@libs : 如果libs为数组变量,该选项可以出现多次,期值被存入数组。

6. ‘flag=s’ : “=”表示该选项后跟字符串(s),整数(i)或浮点数(f)等类型的参数。

7. ‘flag=s’ => \%flags: 如果flags为散列,该选项的参数要求一个键值对(key=value),其值存放到散列中。

说明:参数匹配时,忽略大小写;其选项可以使用简写形式(唯一最短字符串,如首字母:-m表示 -more)

Getopt程序执行方法:

假设上述代码保存在test.pl文件中,chmod +x test.pl。

$./test.pl --verbose --verbose -v --monitor --lib='/lib' -l '/lib64' --f a=1 --flag b=2  --debug 2 -t random


执行上述代码,可以得到如下结果:

verbose=3, monitor=1, debug=2, test=random, libs=/lib /lib64
a=>1
b=>2


Getopt::Long模块传递参数:

1. 参数类型:s为字符串,i为整数,f为浮点数

2. 变量类型:$为普通变量,@为数组,%为哈希
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: