Parsing keyword=value pairs

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm looking to have an input file that has keyword=value pairs. I've
been moving along the "roll your own" path, but I am looking for a
little guidance to the most effective way. The input file will have a
series of parameters, like:


I was thinking that the rest of the program would setup a hash, where
the lvalue is the key and the rvalue is the value, which I think makes
sense. I thought I could also have a list of "required" keys and
"optional" keys to aid in processing.

So - anyone have some suggestions on a good way to read the input file
of pairs?


Re: Parsing keyword=value pairs

Quoted text here. Click to load it

That looks very much like a plain old standard INI file. I didn't check
but I would be very surprised if was no existing parser for INI-files on


Re: Parsing keyword=value pairs

pgodfrin wrote:
Quoted text here. Click to load it

You could do something like the following:

use strict;
use warnings;
use File::Slurp;

my $inifile = 'test.ini';
my @mandatory = qw(name city);

die "Ini file '$inifile' not accessible!"
     unless( -r $inifile );

my $ini = read_file($inifile);

my %cfg = ( $ini =~ /^([^=]+)=(.*)$/mg );

foreach( @mandatory ) {
     die "Missing or empty config option '$_'"
         unless( $cfg );

Though if your requirements get more complex or you need additional
validation of values, looking at CPAN is the way to go.


Re: Parsing keyword=value pairs

  CW> use File::Slurp;

  CW> die "Ini file '$inifile' not accessible!"
  CW>      unless( -r $inifile );

no need for that test, read_file will die with an error by default.

  CW> my $ini = read_file($inifile);
  CW> my %cfg = ( $ini =~ /^([^=]+)=(.*)$/mg );

you can merge those two lines together - no need for the temp var:

    my %cfg = read_file($inifile) =~ /^([^=]+)=(.*)$/mg ;

that idiom is the fastest and one of the simplest ways to parse a simple
key/value file.


Uri Guttman  ------  -------- --
-----  Perl Code Review , Architecture, Development, Training, Support ------
--------- Free Perl Training --- ---------
---------  Gourmet Hot Cocoa Mix  ---- ---------

Re: Parsing keyword=value pairs

pgodfrin schrieb:
Quoted text here. Click to load it

You can also use one of those CPAN modules, they seem to do the trick
for me.  They are normally used to read .ini files, but if you just
extract the first section (either an empty string or "_") you have your

use Config::IniHash;
my %hash = %;

   'city' => 'london',
   'car' => 'sedan',
   'name' => 'foobar'


use Config::INI::Reader;

my %hash = %;

   'city' => 'london',
   'car' => 'sedan',
   'name' => 'foobar'

Marc "Maluku" Lucksch

Re: Parsing keyword=value pairs

In article
Quoted text here. Click to load it

    use Config::Properties;

Tim McDaniel,

Site Timeline