Next | Lightweight Databases | 14 |
This version (which we saw earlier) is safer:
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 or die ...; close $wfh or die ...; rename "$file.tmp", $file or die ...; }
rename is guaranteed to be atomic:
At every instant, exactly one version of the file exists
If the function fails, or Perl crashes, the old file is untouched
At the moment the rename succeeds, the entire new file is in place
(Warning: file.tmp and file must be on the same filesystem)
Why doesn't -i do it this way?
No good reason; coming in 5.10.
Next | Copyright © 2003 M. J. Dominus |