User Tools

Site Tools


configreader

Perl Pseudo XML Configreader

This sub reads an configfile and returns it as a Datastructure. The format is similar to the one used by Apache.

FIXME add example config

sub readConfig($){
  my $cfgfile = $_[0];
  open (FILE,$cfgfile) || die("could not open configfile '$cfgfile'");
  my @file = <FILE>;
  close (FILE);
 
  my ($name,$val);
  my %config;
  my $section='';
  my $sname='';
 
  foreach my $line (@file){
    # skip comments
    $line=~ s/#.*$//;
    $line=~ s/^\s*//;
    $line=~ s/\s*$//;
    next if ($line eq '');
    # end of section
    if($line =~ m/<\/\Q$section\E>/i){
      $section = '';
      $sname = '';
      next;
    }
    # start of section
    if($line =~ m/<(\w*)\s?(.*)>/i){
      $section = $1;
      $sname = $2;
      $sname =~ s/^\s*//;
      $sname =~ s/\s*$//;
      if($sname eq ''){
         $config{lc($section)} = undef;
      }else{
         ${$config{lc($section)}}{$sname} = undef;
      }
      next;
    }
    if($section && $sname eq ''){
      #inside nameless section
      if($line =~ m/.+=.+/){
        ($name,$val) = split("=",$line,2);
        $val=~ s/^\s*//;
        $name=~ s/\s*$//;
        ${$config{lc($section)}}{lc($name)}=$val;
      }else{
        push(@{$config{lc($section)}},$line);
      }
    }elsif($section && $sname ne ''){
      #inside named section
      if($line =~ m/.+=.+/){
        ($name,$val) = split("=",$line,2);
        $val=~ s/^\s*//;
        $name=~ s/\s*$//;
        ${${$config{lc($section)}}{$sname}}{lc($name)}=$val;
      }else{
        push(@{${$config{lc($section)}}{$sname}},$line);
      }
    }else{
      #no section
      ($name,$val) = split("=",$line,2);
      $val=~ s/^\s*//;
      $name=~ s/\s*$//;
      $config{lc($name)}=$val;
    }
  }
 
  return %config;
}
configreader.txt · Last modified: 2005/10/28 08:52 by 84.56.209.62