Simple configuration file parser
- config.pl
#!/usr/bin/env perl
package Config;
use strict;
use warnings;
sub new {
my ($class, $file) = @_;
my $self = {
file => $file
};
bless $self, $class;
$self;
}
sub file {
my ($self, $name) = @_;
return $self->{'file'} unless $name;
$self->{'file'} = $name;
$self;
}
sub read {
my $self = shift;
return undef unless -r $self->file;
open my $fh, '<', $self->file;
my %res;
while (my $line = readline $fh) {
chomp $line;
$line =~ s/^\s+//g;
next if $line =~ /^#/;
next if $line =~ /^;/;
next unless $line =~ /=/;
my ($key, $rawvalue) = split(/==|=>|[=:]/, $line);
next unless $rawvalue and $key;
my ($value, $comment) = split(/[#;]/, $rawvalue);
$key =~ s/^\s+|\s+$//g;
$value =~ s/^\s+|\s+$//g;
$res{$key} = $value;
}
\%res;
}
1;
use strict;
use warnings;
use Mojo::Util qw(dumper);
my $c = Config->new('config.ini');
print dumper $c->read;
#my $c = Config->new('config.ini');
#print dumper Config->newread;
#EOF
Sample config
#
# $Id$
#
a = 12
b = qwe
c = abc
a = 1234
zzz =
xxx
t1 = 123 # comment
; comment
t2 == 456 ; comment
# comment
t3 => 789 ; comment
;comment
#EOF
Result