| Next | Lightweight Databases | 7 |
The simplest and most often-cited solution is to copy the file
Make the changes as you write the copy
Then replace the original with the copy
For example, deleting billg:
sub delete_user {
my ($file, $target_user) = @_;
open my $rfh, "<", $file or die ...;
open my $wfh, ">", "$file.tmp" or die ...;
while (<$rfh>) {
my ($user) = split /:/;
print $wfh unless $user eq $target_user;
}
close $rfh; close $wfh or die ...;
rename "$file.tmp", $file or die ...;
}
Or appending to a log file:
sub append_log {
my ($file, @newrecs) = @_;
open my $rfh, "<", $file or die ...;
open my $wfh, ">", "$file.tmp" or die ...;
my @recs = (<$rfh>, @newrecs);
splice @recs, 0, @recs-$MAXRECS if @recs > $MAXRECS;
print $wfh @recs;
close $rfh; close $wfh or die ...;
rename "$file.tmp", $file or die ...;
}
| Next | ![]() |
Copyright © 2003 M. J. Dominus |