通过perl处理INI文件的步骤

通过perl处理INI文件的步骤

#!/usr/bin/perl

#usage:
# my %hash=iniToHash('/tmp/myini.ini');
# print $hash{'TITLE'}->{'Name'},"/n";
#
sub iniToHash{
open(MYINI,$_[0]);
my %hash1;
my $hashref;
while( <MYINI> ){
if( my($key) = //[(.+)/]/ ){
$hashref = $hash1{$key} ||= {};
}elsif( my($k,$v) = /(/S+)/s*=/s*(.+)/ ){
$hashref->{$k}=$v;
}
}
close MYINI;
return %hash1;
}
#usage:
# $hash{'TITLE'}->{'Name'}='John';
# hashToIni(/%hash,'/tmp/myini.ini');
#
sub hashToIni{
my $rootref=$_[0];
open MYINI,">$_[1]";
while (my ($key, $value) = each (%{$rootref})) {
print MYINI "[$key]/n";
while(my ($subkey, $subvalue) = each (%{$value})){
print MYINI "$subkey = $subvalue/n";
}
}
close MYINI;
}
my %root=iniToHash('d:/test.ini');
print $root{'TITLE'}->{'Name'},"/n";
my %testhash;
$testhash{'testname'}='testvalue';
$root{'test'}=/%testhash;
hashToIni(/%root,'d:/test.ini');