tags:

views:

674

answers:

5

What is the best way to parse INI file in Perl and convert it to hash?

+5  A: 

Config::INI::Reader

David Dorward
+5  A: 

If you like more perlish style then try Tie::Cfg. Sample:

tie my %conf, 'Tie::Cfg', READ => "/etc/connect.cfg";

$conf{test}="this is a test";
Ivan Nevostruev
+4  A: 

Config::Tiny is very easy and straightforward to use.

$Config = Config::Tiny->read( 'file.conf' );

my $one = $Config->{section}->{one};
my $Foo = $Config->{section}->{Foo};
Paul Nathan
+6  A: 

I prefer to use Config::IniFiles module.

depesz
Config::IniFiles is a very powerful INI manager. Good recommendation.
daotoad
+2  A: 

The best way is to make use of available modules in CPAN as what others have suggested. Below is just for your own understanding, let's say you have ini file like this:

$ more test.ini
[Section1]
    s1tag1=s1value1             # some comments
[Section2]
    s2tag1=s2value1           # some comments
    s2tag2=s2value2
[Section3]
    s3tag1=s3value1

you can do your own parsing w/o modules by using just Perl's regex (or string methods) + data structures like hashes.

Sample Code:

   $ini="test.ini";
    open (INI, "$ini") || die "Can't open $ini: $!\n";
        while (<INI>) {
            chomp;
            if (/^\s*\[(\w+)\].*/) {
                $section = $1;
            }
            if (/^\W*(\w+)=?(\w+)\W*(#.*)?$/) {
                $keyword = $1;
                $value = $2 ;
                # put them into hash
                $hash{$section} = [ $keyword, $value];
            }
        }
    close (INI);
    while( my( $k, $v ) = each( %hash ) ) {
        print "$k => " . $hash{$k}->[0]."\n";
        print "$k => " . $hash{$k}->[1]."\n";
    }

output

$ perl perl.pl
Section1 => s1tag1
Section1 => s1value1
Section3 => s3tag1
Section3 => s3value1
Section2 => s2tag2
Section2 => s2value2
ghostdog74