-4

What is the best way to parse ini files in Perl?

the file is formated in this way:

[group1]
value1
value2
value3

[group2]
value1
value2
value3
value4

[group3]
value1
value2
dean
  • 1
  • 1
  • 1
    Looks like there's options on CPAN for reading them. [Config::INI](https://metacpan.org/pod/Config::INI) etc. – Shawn Sep 20 '18 at 20:39
  • 1
    Config::IniFiles – Andrey Sep 20 '18 at 20:42
  • I have looked but the format is different. most expect a "param=value" format – dean Sep 20 '18 at 20:47
  • 2
    If it doesn't have a `param=value` format, then [it's not an INI file](https://en.wikipedia.org/wiki/INI_file), and your question is "How do I parse something that is sort of but not quite like an INI file?" – mob Sep 20 '18 at 20:54
  • Yes its actually .conf but formatted similar to INI. any suggestions? – dean Sep 20 '18 at 21:01
  • 2
    What have you tried so far? Are you getting any errors? How is the actual output different from the expected output? What isn't working with your existing solution? – Matt Jacob Sep 20 '18 at 23:24

1 Answers1

1

You haven't told us the expected format for the data or shown any existing code, so it's impossible to know what you're looking for, but this should get you at least 90% of the way there:

use strict;
use warnings;

use Data::Dumper;

my %config;
my $group = '';

while (<DATA>) {
    chomp;
    next unless /\S/;

    if (/^\[([^]]+)\]/) {
        $group = $1;
        next;
    }

    push(@{$config{$group}}, $_);
}

print Dumper(\%config);

__DATA__
[group1]
value1
value2
value3

[group2]
value1
value2
value3
value4

[group3]
value1
value2
Matt Jacob
  • 6,503
  • 2
  • 24
  • 27