Parsing keyword=value pairs

P

pgodfrin

Greetings,
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:

name=foobar
city=london
car=sedan

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?

regards,
phil
 
J

Jürgen Exner

pgodfrin said:
Greetings,
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:

name=foobar
city=london
car=sedan

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
CPAN.

jue
 
U

Uri Guttman

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
 
M

Marc Lucksch

pgodfrin said:
name=foobar
city=london
car=sedan
So - anyone have some suggestions on a good way to read the input file
of pairs?

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
data.

use Config::IniHash;
my %hash = %{ReadINI('test.ini')->['']};

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


or

use Config::INI::Reader;

my %hash = %{Config::INI::Reader->read_file('test.ini')->['_']};

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



Marc "Maluku" Lucksch
 
T

Tim McDaniel

Greetings,
I'm looking to have an input file that has keyword=value pairs. ....
So - anyone have some suggestions on a good way to read the input
file of pairs?

use Config::properties;
?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top