I have a configuration file filled with some config vars & values, it looks more like this
[section_name]
var=value
var=value
...
[section_name]
var=val
var=val
...
I have to parse this file & fill a hash var. I have a script to do this, but it does not work in some conditions when the new lines of the config file changes(ex: if i remove a blank line).
dont know y it happens, i need suggestion to improve my code so that it is robust...
Thanks in advance
it will update the hash in this fashion:
hash = (
section_name_0 => val,
section_name_1 => val,
...
);
The keys will have section_name followed by 0 1 2... After each section the count resets to 0(zero) & so on.
Here is the code
sub UpdateConfigHash {
$config_file = $ENV{'CONFPATH'};
open( CONFFILE, $config_file ) || die "$!\n";
my @config_file_contents = <CFILE>;
my $abs_path_section_flag = 0;
my $section_flag = 0;
my $section_name = "";
my $config_files_line = "";
my $config_files_line_ind = 0;
while ( defined( $config_file_contents[$config_files_line_ind] ) )
+ {
$config_files_line = $config_file_contents[$config_files_line_
+ind];
trim_clean( $config_files_line );
if ( $config_files_line =~ /^(\s*)#/ ) {
$config_files_line_ind++;
next;
}
if ( $config_files_line =~ /^(\s*)$/ ) {
$config_files_line_ind++;
next;
}
if ( $config_files_line =~ /^(\d+)$/ ){
$global_settings{"comm_port"} = $&;
$config_files_line_ind++;
next;
}
if ( $config_files_line =~ /^\[abs_paths\]/ ) {
$abs_path_section_flag = 1;
$section_flag = 0;
$config_files_line_ind++;
next;
}
if ( $config_files_line =~ /^\[(\w+)\]/ ) {
$section_name = $1;
$abs_path_section_flag = 0;
$section_flag = 1;
$section_index = 0;
$config_files_line_ind++;
next;
}
if ( $abs_path_section_flag == 1 && $section_flag == 0 ) {
# indicates abs_paths is on
my @temp = split( /=/, $config_files_line );
trim_clean (\$temp[0]);
trim_clean (\$temp[1]);
$global_settings{ $temp[0] } = $temp[1];
$config_files_line_ind++;
next;
}
if ( $abs_path_section_flag == 0 && $section_flag == 1 ) {
# indicates a section ( not abs_paths )
my @temp = split( /=/, $config_files_line );
trim_clean (\$temp[0]);
trim_clean (\$temp[1]);
$global_settings{ $section_name . "_" . $section_index } =
+ $temp[1];
$section_index++;
$config_files_line_ind++;
next;
}
}
}