User Tools

Site Tools


configreader

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

configreader [2005/10/28 10:01]
82.79.122.73
configreader [2005/10/28 10:52] (current)
84.56.209.62 old revision restored
Line 1: Line 1:
 +====== 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
 +
 +<code perl>
 +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;
 +}
 +</​code>​
configreader.txt ยท Last modified: 2005/10/28 10:52 by 84.56.209.62