in reply to Re: In place editing of text files
in thread In place editing of text files

thanks for the explanation!
I solved my little problem by just opening the handle two times: one for read and one for write access:
#!perl -w use strict; my $line; my @array; my $CTLfile = 'y:\perl\test.ctl'; open (CTLHANDLE, "<$CTLfile"); @array = <CTLHANDLE>; close(CTLHANDLE); open (CTLHANDLE, ">$CTLfile"); foreach $line(@array){ $line =~ s/SOURCEREPOSITORYNAME/SOURCEREPOSITORYNAME=Development/g +; print CTLHANDLE "$line"; } close(CTLHANDLE);
this seems to work fine.

Replies are listed 'Best First'.
Re^3: In place editing of text files
by ig (Vicar) on May 29, 2009 at 00:15 UTC

    That will work well for small to moderately sized files: anything that fits in memory, which is quite large these days.It is a good solution in many cases.

    An advantage of writing to a temporary file and renaming is that you are less likely to end up with a truncated or partial file replacing your original. With your method, if your program or the system fails after you open the file for output, which truncates it, and before you finish writing and flushing all your buffers to disk, you will end up with an incomplete file. If you write to a temporary file and only rename it after closing your output file handle the risk of ending up with a truncated file is much much less.

    There is still some risk, even if you write a temporary file, close and rename it. You can reduce the risk further, but not to zero as far as I can tell. Through the various layers of control between your program and the persistent storage medium, it is possible that operations are re-ordered and that abrupt termination (e.g. power loss) can result in corruption despite even extreme measures taken in your program. http://www.gossamer-threads.com/lists/perl/porters/236839 is one writeup on some of these issues.