Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2397985
  • 博文数量: 328
  • 博客积分: 4302
  • 博客等级: 上校
  • 技术积分: 5486
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-01 11:14
个人简介

悲剧,绝对的悲剧,悲剧中的悲剧。

文章分类

全部博文(328)

文章存档

2017年(6)

2016年(18)

2015年(28)

2014年(73)

2013年(62)

2012年(58)

2011年(55)

2010年(28)

分类:

2010-11-10 17:05:02

我们在linux常常用到一个程序需要加入参数,现在了解一下perl中的有关控制参数的函数.getopt.在linux有的参数有二种形式.一种是–help,另一种是-h.也就是-和–的分别.–表示完整参数.-表示简化参数.

在perl中也分这二种.

Getopt::Std模块的功能: 初始化perl命令行中所接受的参数,简化了命令行参数的解析。

简化参数例子:

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/perl -w
use strict;
use Getopt::Std;
 
use vars qw($opt_a $opt_b $opt_c);
getopts('d:f:p:');
 
print "\$opt_a =>; $opt_a\n" if $opt_a;
print "\$opt_b =>; $opt_b\n" if $opt_b;
print "\$opt_c =>; $opt_c\n" if $opt_c;

输出如下:

[root@mail test]# ./getopt.pl -a aa -b bb -c cc

$opt_a =>; aa

$opt_b =>; bb $opt_c =>; cc

 

完整参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
#!/usr/bin/perl
use Getopt::Long;
Getopt::Long::GetOptions(
'page=i' => \$page,
'onoff!' => \$onoff,
'help' => \$wants_help,
'name=s' => \$name,
'number:i' => \$number);
 
}
 
if(defined($page)){ print "page flag set to $page "
}if(defined($onoff)){
print "onoff flag set to $onoff ";
}
if(defined($wants_help)){
print "help flag set to $wants_help ";
}
if(defined($name)){
print "name flag set to $name ";
}
if(defined($number)){
print "number flag set to $number ";
}

./getlong.pl -name AAA
name flag set to AAA

 

带值参数
※参数类型:整数, 浮点数, 字串

GetOptions( ‘tag=s’ => \$tag );
‘=’表示此参数一定要有参数值, 若改用’:'代替表示参数不一定要有参数值
‘s’表示传递字串参数, 若为’i'表传递整数参数, 若为’f'表传递浮点数
example:
test.pl –tag=string
or
test.pl –tag string

 

多参数值的参数

GetOptions ("library=s" => \@libfiles);
参数传到 @tag
or
GetOptions ("library=s@" => \$libfiles);
参数传到 @$tag
example:
test.pl –library lib/stdlib –library lib/extlib

 

参数别名
GetOptions (‘length|height=f’ => \$length);
第一个名称为primary name, 其他的名称为alias(可有多个alias名称)
当使用hash参数时, 使用primary name作为key值

参数的简称及大小写
GetOptions (‘length|height=f’ => \$length, "head" => \$head);
若没有特别设定, Getopt会忽略参数的大小写, 也就是 -l or -L 指的都
是同一个参数(–length)

对于不传递参数的选项,也就是一些开关类型,可以在第一部分后接“!”,这表示该选项不接收自变量,但 是可以 通过在前面加上no变成负的(例如,“more”选项的-nomore)。如果不是用“!”,而是“+”,这表示它会在每次出现的时候增加一个变量。如果 选项出现在命令行里,那么相关的变量被设置为1;如果负的选项出现了,那么相关的变量就被设置为0。

 

hash参数值(有名称及参数值)
GetOptions ("define=s" => \%defines);
or
GetOptions ("define=s%" => \$defines);
example:
test.pl –define os=linux –define vendor=redhat

阅读(1199) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~