martymart has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks, I have an .ini file that I'd like to put into a hash, it's of the format:
$xmldir="c:\test" $cvs="d:\test" %name=lancelot etc.
It's a bit of a mess, with some lines using quotes and others not. I wrote a short script that seems to work fine:
open FILE, "anyfile.ini"||die "file open failed\n"; my %inihash=(); while (my $line = <FILE>) { $line =~ tr/"//d; (my $key, my $value)=split(/=/,$line); $inihash{$key}=$value; }; print "$inihash{'$xmldir'}"; print "$inihash{'$cvs'}"; print "$inihash{'%name'}";
But, there must be a more efficient way of doing this, possibly using Config::IniFiles or some other code improvements. I'm open to any ideas that my fellow monks could suggest (comments, criticisms, etc.) Thanks in advance.

Replies are listed 'Best First'.
Re: Reading .ini files
by Mr. Muskrat (Canon) on Nov 25, 2002 at 16:27 UTC

    Config::IniFiles would be my choice. It's easy to use especially when you tie it to a hash.

    #!/usr/bin/perl use strict; use warnings; use Config::IniFiles; my %ini; tie %ini, 'Config::IniFiles', ( -file => "anyfile.ini" ); # Parameters are accessible like this: $ini{Section}{Parameter} foreach my $section ( keys %ini ) { my @parameters = keys %{$ini{$section}}; # do something with the @parameters for this $section }

Re: Reading .ini files
by Wonko the sane (Curate) on Nov 25, 2002 at 16:35 UTC
    Config::IniFiles would definitely be my first choice for doing this effectively in production code.
    Here is a map and regex solution to the same problem though.

    #!/usr/local/bin/perl use strict; use Data::Dumper; my %info = map { /^(\S+)\s*=\s*"?(.+?)"?$/ } <DATA>; print Dumper( \%info ); __DATA__ key1="value1" key2=value2 key3 = value3 key4 =value4 key5 = "value5"

    Wonko