Created
April 27, 2015 21:13
-
-
Save rkleemann/59943aadcde8e855b56a to your computer and use it in GitHub Desktop.
Simple configuration file parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v5.18; # Why 5.18? Because that's what I'm used to. | |
package SimpleConfig; | |
use boolean; | |
use File::Slurp; | |
use Scalar::Util qw(looks_like_number); | |
sub parse_line { | |
my $line = shift; | |
return if $line =~ /^\s*#/; | |
my ($k, $v) = map { s/^\s*//r =~ s/\s*$//r } split /=/, $line, 2; | |
return unless ( length $k && defined $v ); # Badly formatted line, skip it for now. | |
if ( $v =~ /^(?:on|true|yes)$/i ) { | |
$v = true; | |
} elsif ( $v =~ /^(?:off|false|no)$/i ) { | |
$v = false; | |
} elsif ( looks_like_number($v) ) { | |
$v = 0+ $v; | |
} | |
return $k => $v; | |
} | |
sub parse_file { | |
my %config = map { parse_line($_) } read_file(shift); | |
return \%config; | |
} | |
sub parse_string { | |
my $string = shift; | |
$string = $$string if 'SCALAR' eq ref $string; | |
my %config = map { parse_line($_) } split /(?:\r?\n)+/, $string; | |
return \%config; | |
} | |
=head1 NAME | |
SimpleConfig - parse a simple configuration file. | |
=head1 SYNOPSIS | |
use SimpleConifg; | |
my $config = SimpleConfig::parse_file('somefile.config'); | |
say $config->{server_id}; # 55331 | |
say $config->{test_mode}; # 1 | |
=head1 DESCRIPTION | |
This will parse a simple congif file, such as the following: | |
# This is what a comment looks like, ignore it | |
# All these config lines are valid | |
host = test.com | |
server_id=55331 | |
server_load_alarm=2.5 | |
user= user | |
# comment can appear here as well | |
verbose =true | |
test_mode = on | |
debug_mode = off | |
log_file_path = /tmp/logfile.log | |
send_notifications = yes | |
It will ignore comment lines; | |
convert numbers (55331, 2.5) to actual numbers, | |
not just string representations of those numbers; | |
booleans (on/off, yes/no, true/false) will be converted | |
to their respective truthiness; | |
and everything else will be left as a string. | |
=head1 AUTHOR | |
Bob Kleemann <bobk@cpan.org> | |
=cut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment