Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

parsing - Parse INI in Perl (list format)

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...