Update: Sigh. Seeing your reply to RollyGuy, maybe all you want is to backwhack the slash or backslash like so:
perl -pi -e's/\{\/rtf1\}//g' /path/to/file.ini
</Update>
The basic method for that is to read the old file, make your modifications, then write the result to a either a new file or over the old one, and finally rename the new file, if used, over the old. There are several reasons to take all those steps.
- You must not clobber the old file with an ordinary open to write, since you need to read it.
- More than one instance of your application may be running, so you need to protect against interference between them.
The interference can happen several ways. A newly started instance may read its configuration from a half-written file. An instance may try to rewrite the configuration and find an empty file for a basis, if another instance is doing the same. These conditions are called races.
Whether you write to a copy and rename depends on whether you read the whole file into memory, or edit as a stream. Both techniques demand care with file locking.
Here is a single file technique: use Fcntl qw( :flock );
{
my $ini;
open $ini, '+<', "$path/$fname" or die $!;
flock $ini, LOCK_EX;
my @lines = <$ini>;
seek $ini, 0, 0;
print $ini edit(@lines) or die $!;
close $ini or die $!;
}
I've assumed some sub edit is defined which returns a list of lines for the new file.
In some circumstances it may be useful to use sysopen since it permits file modes that are unavailable with open. For a stream edit, this technique is like the edit mode '-pi=bak' available from the command line: use Fcntl;
{
my {$in,$out);
sysopen $out, "$path/$fname.bak",
O_WRONLY | O_CREAT | O_EXCL | O_EXLOCK
or sleep 1 and redo;
open $in, '<', "$path/$fname" or die $!;
flock $in, LOCK_EX;
while (<$in>) {
# edit operations to modify or skip $_
print $out or die $!;
}
close $in;
close $out or die $!
rename "$path/$fname.bak", "$path/$fname" or die $!;
}
Here, output file locking is done with the combination of flags in sysopen. The use of O_EXCL with rename is worth study.
I've used some Perl 5.6 -isms with lexical handles and 3-arg open, but all this can be done with global handles and two arg open, as well.
After Compline, Zaxo
|