On Thu, Dec 27, 2001 at 09:19:16AM -0600, Steve Langasek wrote:
<chomp />
> My own approach?  Write your own parser for a simple 'key = value' style 
> config file.  This can usually be done in ten lines or less[1] using
> perl's powerful regexp engine.
<chomp /> 
> [1] depending, of course, on your standards for code legibility ;)


Something like:

<code>
my $config = "/etc/perl-passwd.conf";     # Or whatever
my $options = {};                         # Not a hash, a reference to a hash
open CONFIG, $config or die "Cannot open $config: $!";
while (<CONFIG>) {
        next if /^(#.*)?$/;               # skip comments, blanks
        if (/^\s*(\w+)\s*=\s*(.+)\s*/) {  # Match "blah = foo bar"
                $options->{$1} = $2       # Set out reference to hash
        } else {
                warn "Error: $_";         # Complain otherwise...
        }
}
close CONFIG;                             # Move along, nothing to see here...
                                          # Now use $options for your config
                                          # but do more sanity checking on the 
                                          # values of each key!
</code>

... and if you don't want the sanity check on the key = value, just use 
"$options->{$1} = $2 if (/^\s*(\w+)\s*=\s*(.+)\s*/);" at line 6.

Then you get to do things like setting options (keys) to arrays of values, 
having user config files override system ones and/or vice-versa, and other fun 
games; left as an exercise to the reader...


  James

BTW, for those who have the Camel 5 book edition 2: make sure you take a 
peek at the edition 3; its about double the pages, lots of cool stuff...
-- 
 James Bromberger <james_AT_rcpt.to> www.james.rcpt.to
 Australian Debian Conference: http://www.linux.org.au/conf/debiancon.html
 Remainder moved to http://www.james.rcpt.to/james/sig.html

Attachment: pgpsuZ24lsr8l.pgp
Description: PGP signature

Reply via email to