Another solution, taking back the idea of a simple key=value file, using a hash, but directly reading from and writing to file, without using File::Tie neither another existing module.
# SimplestConfig.pm # SimplestConfig->new('filename') returns an object whose attributes # (simple values only at this time) will be stored in a file named # filename under the form attribute=value and as such may be usefull # to manage simple config files. use strict; use warnings; package SimplestConfig; sub new { my ($class, $filename) = @_; my $self = {_FileName_ => $filename}; bless $self, $class; if (open CFG, "<$filename") { while (<CFG>) { /^\s*(\S.*?)\s*=\s*(.*?)\s*$/ and $self->{$1} = $2; } close CFG; } else { warn "Can't read $filename, creating it\n"; } return $self; } sub DESTROY { my ($self) = @_; open CFG, ">$self->{_FileName_}" or die "Can't write $self->{_FileName_}\n"; delete $self->{_FileName_}; print CFG map "$_=$self->{$_}\n", sort keys(%{$self}); close CFG; } 1;
#!/usr/bin/perl -w # test1.pl use strict; use lib "$ENV{HOME}/perl"; use SimplestConfig; my $cfg = SimplestConfig->new("$ENV{HOME}/test.cfg"); $cfg->{a} = 1; $cfg->{b} = 2; $cfg->{c} = 3;
#!/usr/bin/perl -w # test2.pl use strict; use lib "$ENV{HOME}/perl"; use SimplestConfig; my $cfg = SimplestConfig->new("$ENV{HOME}/test.cfg"); $cfg->{b} = 20; $cfg->{d} = 4;
Test:
$ more test.cfg test.cfg: No such file or directory $ ./test1.pl Can't read /home/laurent/test.cfg, creating it $ more test.cfg a=1 b=2 c=3 $ ./test2.pl $ more test.cfg a=1 b=20 c=3 d=4
Note it would discard any line not of the form key=value from an existing file.
And on another subject, Happy New Year to everybody.
In reply to Re: Managing config files
by linkeditor
in thread Inserting lines in a file with Tie::File if lines don't exist
by devgoddess
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |