I agree that using an ini-parsing module as mentioned is preferable. Nevertheless, perhaps the following will be helpful:
use strict;
use warnings;
use Data::Dumper;
my ( $block, %hash );
while (<DATA>) {
$block = $1 if /\[(.+)\]/;
$hash{$block}{$1} = $2 if /(\S+?)\s*=\s*(\S+)/ and defined $block;
}
print Dumper \%hash;
__DATA__
[strings]
variables=BUILDID,MAJOR
[BUILDID]
VALUE=898
VERSION.H=/home/src/gd_version.h
readme=/home/src/readm.txt
[MAJOR]
VALUE=8
IGD2.H=/home/src/igd2.h
readme=/home/src/readm.txt
license=/usr/src/license.html
Output:
$VAR1 = {
'BUILDID' => {
'VERSION.H' => '/home/src/gd_version.h',
'VALUE' => '898',
'readme' => '/home/src/readm.txt'
},
'MAJOR' => {
'VALUE' => '8',
'readme' => '/home/src/readm.txt',
'license' => '/usr/src/license.html',
'IGD2.H' => '/home/src/igd2.h'
},
'strings' => {
'variables' => 'BUILDID,MAJOR'
}
};
To access individual values, use the following pattern:
my $value = $hash{'block'}{'key'};
For example:
print $hash{'BUILDID'}{'VERSION.H'};
Output:
/home/src/gd_version.h
In case you would like to try a different ini module, Config::IniFiles will create the same HoH as above:
use strict;
use warnings;
use Config::IniFiles;
tie my %hash, 'Config::IniFiles', ( -file => 'config.ini' );
print $hash{'BUILDID'}{'VERSION.H'};
Output:
/home/src/gd_version.h
If you don't know the contents of the ini file, but still want to access the values, you can do the following--given the HoH from above:
for my $block ( keys %hash ) {
print "$block:\n";
for my $key ( keys %{ $hash{$block} } ) {
print "$key => $hash{$block}{$key}\n";
}
print "\n";
}
Output:
BUILDID:
VERSION.H => /home/src/gd_version.h
VALUE => 898
readme => /home/src/readm.txt
MAJOR:
VALUE => 8
readme => /home/src/readm.txt
license => /usr/src/license.html
IGD2.H => /home/src/igd2.h
strings:
variables => BUILDID,MAJOR
Instead of using a tied hash, you can use Config::IniFiles's methods for data access:
use strict;
use warnings;
use Config::IniFiles;
my $cfg = Config::IniFiles->new( -file => 'File.txt' );
my @sections = $cfg->Sections;
for my $section (@sections) {
print $section, "\n";
my @parms = $cfg->Parameters($section);
for my $param (@parms) {
print "$param => ", $cfg->val( $section, $param ), "\n";
}
print "\n";
}
Output:
strings
variables => BUILDID,MAJOR
BUILDID
VALUE => 898
VERSION.H => /home/src/gd_version.h
readme => /home/src/readm.txt
MAJOR
VALUE => 8
IGD2.H => /home/src/igd2.h
readme => /home/src/readm.txt
license => /usr/src/license.html