Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Parsing an Arbitrary "config" file (based on a "template"?)

by roboticus (Chancellor)
on Dec 31, 2014 at 22:22 UTC ( [id://1111870]=note: print w/replies, xml ) Need Help??


in reply to Parsing an Arbitrary "config" file (based on a "template"?)

three18ti:

If it's always that format, you don't need anything fancy. Just read the file, split each line into two chunks at the first colon, and package it all up into a hash. It should be something like this:

sub read_config_file { my $file_name = shift; open my $FH, '<', $file_name or die "Can't read $file_name: $!\n"; my $result = {}; while (my $line = <$FH>) { my ($key, $value) = split /:/, $line, 2; $value =~ s/\r?\n$//; $result->{$key} = $value; } return $result; } my $config_data = read_config_file('config_file_name.cfg'); print "Daily mission: ", $config_data->{'What are we doing today Brain +'}, "\n"; print "Location: ", $config->data{where}, "\n";

(Note: untested...)

Update: I actually like Marpa::R2 a good bit. I just did a project at work with it last month where I had to write a parser for a programming language. I found it to be pretty nice to use in that capacity. But it's overpowered, in my opinion, if you have simple tag:value pairs in a configuration file.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Parsing an Arbitrary "config" file (based on a "template"?)
by roboticus (Chancellor) on Dec 31, 2014 at 23:33 UTC

    OK, I got a little bored at work, so I thought I'd code it up in Marpa just as an example. There's a minor bug in it, but I'll leave it in there. Source code:

    When I run it, I get:

    $ perl parse_cfg_file.pl Daily mission: Same thing we do every day Pinky Location: October All configuration data: { "baz" => "1234+54q - bar bar", "foo" => "bar", "Some other parameter" => 42, "What are we doing today Brain" => "Same thing we do every day Pinky +", "where" => "October", "who" => "bob", }

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      This is great thanks!

      I do see what you mean about it being a bit overpowered, but it is clean.

      I especially like:

      $value =~ s/\r?\n$//;

      from your first example.

      I wonder which will be more maintainable in the long run.

      Thanks for the examples!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-20 04:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found