The real answer to this is to use Config::Tiny
.
However, since this is an learning exercise assigned by your teacher, I will point you at all of the perlfaq5: How do I change, delete, or insert a line in a file, or append to the beginning of a file?
. That should demonstrate all of the standard ways to manipulate a file.
If it wasn't also a module, I'd recommend using the core library Tie::File
for this problem, but that's probably not your teachers intent.
So my final recommendation is to take a look at the source for Config::Tiny
. It's likely to be outside of your skill set, but ideally you would be able to read this entire file by the end of your course. And this problem does not take a complicated bit of code. Looking at how others have solved problems can be oen of the best ways to learn, especially if you're able to recognize which are the better modules.
Update
Config::Tiny
alone will not be able to a parse your file, because it's not a strict ini file format. The fact that one of your sections has raw values without keys won't work with any of the standard modules.
Below is an example of how to parse your file using regular expressions. Probably should be enhanced with additional error checking to make sure key/value pairs aren't mixed with array values, but this should get you started:
use strict;
use warnings;
my %hash;
my $section;
while (<DATA>) {
chomp;
next if /^\s*$/;
# Begin Section
if (/^\s*\[(.*)\]\s*$/) {
$section = $1;
# Hash Key & Value
} elsif (/^(.*?)=(.*)/) {
$hash{$section}{$1} = $2;
# Array
} else {
push @{$hash{$section}}, $_;
}
}
use Data::Dump;
dd \%hash;
__DATA__
[ConferenceId]
1000
2000
3000
4000
[RadioExt]
1000=102
2000=202
3000=302
4000=402
Outputs:
{
ConferenceId => [1000, 2000, 3000, 4000],
RadioExt => { 1000 => 102, 2000 => 202, 3000 => 302, 4000 => 402 },
}