What is the best way to parse INI file in Perl and convert it to hash?
reading and write function for ini file edit:
sub iniRead
{
my $ini = $_[0];
my $conf;
open (INI, "$ini") || die "Can't open $ini: $!\n";
while () {
chomp;
if (/^\s*\[\s*(.+?)\s*\]\s*$/) {
$section = $1;
}
if ( /^\s*([^=]+?)\s*=\s*(.*?)\s*$/ ) {
$conf->{$section}->{$1} = $2;
}
}
close (INI);
return $conf;
}
sub iniWrite
{
my $ini = $_[0];
my $conf = $_[1];
my $contents = '';
foreach my $section ( sort { (($b eq '_') <=> ($a eq '_')) || ($a cmp $b) } keys %$conf ) {
my $block = $conf->{$section};
$contents .= "\n" if length $contents;
$contents .= "[$section]\n" unless $section eq '_';
foreach my $property ( sort keys %$block ) {
$contents .= "$property=$block->{$property}\n";
}
}
open( CONF,"> $ini" ) or print("not open the file");
print CONF $contents;
close CONF;
}
sample usage:
read conf file and saved to hash
$conf = iniRead("/etc/samba/smb.conf");
change the your config attribute or added new config attributes
edit
$conf->{"global"}->{"workgroup"} = "WORKGROUP";
added new config
$conf->{"www"}->{"path"}="/var/www/html";
saved your new configuration to file
iniWrite("/etc/samba/smb.conf",$conf);