Skip to content

Instantly share code, notes, and snippets.

@penryu
Created January 18, 2011 05:36
Show Gist options
  • Save penryu/784026 to your computer and use it in GitHub Desktop.
Save penryu/784026 to your computer and use it in GitHub Desktop.
parse simple INI-style config file without eval or non-standard modules
#!/usr/bin/perl -wT
# No non-standard modules.
# Not ideal for non-simple field names;
# suggest a split-based algo for those.
# *shrug* I got bored.
use strict;
my $cfg_file = "testdata.cfg";
my %cfg = ();
open my $cfg_fh, "<", $cfg_file
or die "can't open '$cfg_file': $!";
while (<$cfg_fh>) {
next if /^\s*#/; # ignore comments
s/^\s*//; s/\s$//; # strip leading and trailing whitespace
if (/^(\w+)\s*=\s*(.*)$/) {
# data parsed without eval
$cfg{$1} = $2;
}
}
close $cfg_fh or warn "can't close '$cfg_file': $!";
use Data::Dumper;
print Dumper(\%cfg);
__END__
# sample data
foo = bar
baz =bar
bar= co
alice=primary
bob =
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment