Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Reading .ini files

by martymart (Deacon)
on Nov 25, 2002 at 16:13 UTC ( [id://215660]=perlquestion: print w/replies, xml ) Need Help??

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 (Deacon) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://215660]
Approved by valdez
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-09-18 11:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The PerlMonks site front end has:





    Results (24 votes). Check out past polls.

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.