Parses a config file in the format of tag=value.
open(CONFIG,"config_file") or die $_; while (<CONFIG>) { chomp; next if /^\s*\#/; next unless /=/; my ($key, $variable) = split(/=/,$_,2); $variable =~ s/(\$(\w+))/$config{$2}/g; $config{$key} = $variable; }

Replies are listed 'Best First'.
RE: Config file parser
by chromatic (Archbishop) on Apr 17, 2000 at 02:08 UTC
    I don't see the purpose of the last substitution there. If you already have potential $values stored in the %config hash, why associate them with new keys?

    Also, why is your Config file referring to variable names as values? If you could provide us with a small application and example config file, that might clear up my questions. :)

RE: Config file parser
by turnstep (Parson) on Apr 17, 2000 at 02:55 UTC
    The purpose is for a configuration file that references earlier keys. For example:
    sub=salami mayo=yes tuna=fish topping=$sub mustard=no

    In this example, $config{'topping'} is set to "salami", not "$sub". The only advice I have for the script is to move the chomp until after the "next"s as there is no need to chomp lines you are bypassing. Other than that, a very nice little script.

      Neat and powerful.

      One quibble-- if you had a non-word character in there, like so:

      foo=hello fruit=apple foo.bar=tunafish color=red baz=$foo.bar
      Then it would turn it into
      baz=hello.bar
      instead of
      baz=tunafish

      Still, it's a powerful technique, and I like it. It gives config-files a Makelike capability. You could say:

      SCRIPT_DIR=/usr/local/scripts MAIN_SCRIPT=$SCRIPT_DIR/main_script.pl
      and then get:
      MAIN_SCRIPT=/usr/local/bin/scripts/main_script.pl

      You could probably answer the above objection by putting bracket support into it, like so (untested):

      $value =~ s/\$ ( {\.+?} | \w+)/$config{$2}/gx;
      That way, we could handle my previous example like so:
      foo=hello fruit=apple foo.bar=tunafish color=red baz=${foo.bar}
Re: Config file parser
by Anonymous Monk on Jan 07, 2003 at 21:32 UTC
    This doesn't account for whitespace on either side of the =, which is too strict for my taste, so i changed the split line to this:
    my ($key, $variable) = split(/\s*=\s*/,$_,2);
RE: Config file parser
by kop (Initiate) on May 13, 2000 at 02:35 UTC
    Hey, I believe that in most cases all you want to do is to simply define some variables... Here's a stupid lilttle routine for reading a config file with one 'variablename=value' per line. One can even #-comment lines out in the config file as well ;-)
    # usage: readConfig("filename") # returns: num. of parameters set sub readConfig { my $filename=shift; my $i=0; if(open(CONF, $filename)) { while(<CONF>) { if(/^\s*(\S+)\s*=\s*([^(#*|\s*)]+)/) { $$1=$2; ++$i; } } return($i); } else { return(0); } }
RE: Config file parser
by princepawn (Parson) on Jul 31, 2000 at 17:14 UTC
    What's wrong with AppConfig?