On Dec 2, 2003, at 7:55 AM, Rod wrote:
What is the best way to read a config file for a perl script. I have some very ugly code that can do it, but I would like to find something cleaner.
I like the Config::General module someone has recommended, amongst the trade offs that one will have to resolve is how much Stuff do you need, and how to access that stuff, and how much 'generic parsing' as opposed to tailered parsing.
remember that 'art is in the eye of the beholder'.
My favorite way is in an OO'ish form where I start with something on the order of
my $web_config = new Dtk::...::ToolConf;
Then actually read them with
#------------------------ # sub set_values { my ($me) = @_; my $error = $me->webadmin_conf_file_name() unless $me->{file}; return $error if (ref($error) eq 'HASH'); open(FD, $me->{file}) or return({runtime_error => "unable to open config file $me->{file} : $!\n"});
while(<FD>) { chomp; s/#.*//; # strip comments next if /^\s*$/; if (/=/ ) { s/\s+=/=/; # clean spaces before = s/=\s+/=/; # clean spaces after = s/\s+$//; # clean trailing spaces s/^\s+//; # clean leading spaces my ($k, $v) = split(/=/); $me->{$k} = $v; } } close(FD); $me->{values_set} = 1; 0; } # end of set_values
And of course have a list of named accessors:
#------------------------ # The Accessors #------------------------
sub config_sufix { $_[0]->{config_sufix} } sub config_dir { $_[0]->{config_dir} } sub bin_dir { $_[0]->{bin_dir} } sub webmin_root { $_[0]->{web_admin_root} } sub webmin_port { $_[0]->{web_admin_port} } sub db_url { $_[0]->{db_url} }
and some other junk that has to do with sanity checking, and displaying them so that the config file can be edited and updated, and yada-yada-yada.
{ yes, could have used AutoLoader - tried that, it didn't take me where I wanted to go.... }
A part of the question you really want to ask is how complex a config file do you want to begin with, and can you live with the issues that come from using a hash where the 'key/value' pairs are accessed directly by the calling code.
Do you need to have complex configuration stuff, if so why not lookt at the LibXml approach...
ciao drieux
---
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]