in reply to Inserting lines in a file with Tie::File if lines don't exist

Not for the low level problem of inserting lines in a file, but for the general purpose of managing a configuration file, you might also consider using a dedicated module.

A quick search on CPAN leads for example on those ones :

Parse::PlainConfig may be the most interesting in this case, as it allows both to write the configuration file and to store lists (were they of servers or of something else) and even hashes.

Replies are listed 'Best First'.
Re: Managing config files
by linkeditor (Initiate) on Jan 01, 2004 at 00:21 UTC

    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.