perl 读写配置文件
发布时间:2020-12-16 00:33:32 所属栏目:大数据 来源:网络整理
导读:? 1.配置文件格式形式如下 ? [NEWBIN] path = /data1/vshare/newbin uid = root gid = root read only = no? [col] path = /data1/col uid = root gid = root read only = no 2.读配置函数 read_conf() 读出为整个hash $hash{"NEWBIN"}{"path "}= “/data1/v
? 1.配置文件格式形式如下 ? #! /usr/bin/perl use RW_Conf; $cup = new RW_Conf(); $cup->setfilename("my.conf"); # my %ret = $cup->read_conf(); # foreach my $cat( keys %ret){ # foreach my $key( keys %{$ret{$cat}}){ my $value=$ret{$cat}{$key}; # print "[".$cat."]".$key."=".$value,"n"; # } # } #my $cat="lady_high"; #my %ret = $cup->read_cat($cat); # foreach my $key( keys %ret ){ # my $value=$ret{$key}; # print "[".$cat."]".$key."=".$value,"n"; # } #my $cat="lady_high"; #my $key="vcodec"; #my $value = $cup->read_cat_key($cat,$key); #print "[".$cat."]".$key."=".$value,"n"; my $cat="lady_high"; my $key="xxxxx"; $cup->write_cat_key($cat,"yyyy"); my $cat="lady_high"; my $key="vfopts2"; $cup->write_cat_key($cat,"yyyy");
package RW_Conf; use strict; sub new { my $this = {}; bless $this; return $this; } sub setfilename() { my $this = shift; $this->{"filename"}=shift; } sub getfilename() { my $this = shift; return $this->{"filename"}; } #读配置函数 #read_conf 返回 %hash sub read_conf() { my $this = shift; my %ret=(); open FH,$this->{"filename"} or die("can't not open ".$this->{"filename"}."n"); my $cat=""; my $key=""; while (my $myline = <FH>) { chomp $myline ; next if $myline eq ""; if( $myline =~ /^s*[s*([^=]+)s*]/ ) { $cat=$1; #print $cat,"n"; } elsif ($myline =~ /=/) { my ($key,$value) = $myline =~ /^([^=]+)=(.*)$/; $key =~ s/s//g; $ret{$cat}{$key}=$value; #print "[".$cat."]|".$key."|".$value,"n"; } } close FH; return %ret; } #读大分类函数 #read_cat($cat) #读出为%hash sub read_cat() { my $this = shift; my $find_cat = shift; my %ret=(); open FH,$this->{"filename"} or die("can't not open ".$this->{"filename"}."n"); my $cat=""; my $key=""; while (my $myline = <FH>) { chomp $myline ; if( $myline =~ /^s*[s*([^=]+)s*]/ ) { $cat=$1; #print $cat,"n"; } } close FH; return %{$ret{$find_cat}}; } #读key函数 #read_cat_key($cat,$key) sub read_cat_key() { my $this = shift; my $find_cat = shift; my $find_key = shift; my %ret=(); open FH,"n"; } } close FH; return $ret{$find_cat}{$find_key}; } #写指定数据函数 #write_cat_key($cat,$key) #读出整个配置,替换此value,整个重写回去 sub write_cat_key() { my $this = shift; my $find_cat = shift; my $find_key = shift; my $write_value=shift; my %ret=(); open FH,"n"; } } close FH; $ret{$find_cat}{$find_key}=$write_value; #重写配置文件 open DET,">",$this->{"filename"} || die ("can't not open ".$this->{"filename"}."n"); foreach my $cat( keys %ret){ print DET "[".$cat."]","n"; foreach my $key( keys %{$ret{$cat}}){ my $value=$ret{$cat}{$key}; print DET $key."=".$value,"n"; } } close DET; } 1; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |