perl 读取 配置文件

来源:互联网 发布:数组作为函数形参 编辑:程序博客网 时间:2024/06/07 07:54
perl 读取 配置文件

http://hi.baidu.com/litaosmile/blog/item/72938859764aaf2d2934f04d.html

config-------------------------------
[perl1]
# one=1
two=2
three=3
# four=four=4
five=asd ad 5
asdasdasd
[per2]
# one=1
two=2
three=3
# four=four=4
five=I am lipeng
asdasdasd


perl--------------------------------
#!/usr/bin/perl -w
open CONFIG,"config" || die "open config $!\n";
$session=$ARGV[0];
$key=$ARGV[1];
$flag=0;
while(<CONFIG>)
{
chomp;
if(/^\s*#/ or /^\s*$/){#预处理--过滤注释行和空行
next;

if($flag == 0 && !~/^\[$session\]/ )
{
next;
}
$flag = 1;
if( (!~ /^#/) && (($k,$v) =m/(\w+)=(.*)/) )
{
if($k eq $key)
{
print "I find $k ............... value $v\n";
last;
}
}
else
{
next;
}
if(/^\[/)
{
last;
}

}

1、预处理:
过滤注释行和空行
对所有的行去除注释部分
while(<CFG>){
if(/^\s*#/ or /^\s*$/){ #预处理--过滤注释行和空行
next;
}

s/\s*#.*//; #去除注释部分
start
}

2、全局唯一参数的读取:
采用哈希表的形式进行赋值和取值
$cfg{key}=value;

3、多个相同格式参数组的读取
设置参数组起始标记
标记内部顺序读取或者条件读取

open(CFG,"config.ini") or die "Cannot open the file:$!";
my @lines = <CFG>;
close(CFG);

for(my $i = 0 ; $i < @lines;$i++){
$_=$lines[$i];
if(/^\s*#/ || /^\s*$/){#除去空行和注释行
next;
}

if($lines[$i]=~m/^\s*\[start]/i){
$_=$lines[++$i];

while($lines[$i]!~ m/^\s*\[END]/i){
s/\s*#.*//unless(/^\s*-?password|username/);#去除注释部分,用户名和密码部分例外
if(s/^\s*-?manu.*:\s*//){
chomp;
$manufacturer = $_;   
}
if(s/^\s*-?ipadd.*:\s*//){
chomp;
$ipaddress = $_;
}
if(s/^\s*-?hostname:\s*//){
chomp;
$hostname = $_;
}
if(s/^\s*-?username:\s*//){
chomp;
$username = $_;
}
if(s/^\s*-?password:\s*//){
chomp;
$password = $_;
}
$_=$lines[++$i];
}
 
if($manufacturer =~ m/huawei/){
&telnet_huawei($hostname,$ipaddress,$username,$password);
}
if($manufacturer =~ m/cisco/){
&telnet_cisco($hostname,$ipaddress,$username,$password);
}
if($manufacturer =~ m/netscreen|juniper/){
&telnet_netscreen($hostname,$ipaddress,$username,$password);
}
}#if [start]
}#for

0 0
原创粉丝点击