in reply to Help in read and write to file at a same time in same file.

Let me weigh-in on the side of the group of experienced Monks who likewise advocate the following:

  1. Read from one file, write to a temporary file .   (Consider placing this file in the same location, but with an obviously-different and obviously-temporary filename, e.g. adding an extension to the filename.)   Silently delete any copy that now exists.
  2. Rename the existing file ... add a different extension.
  3. Rename the file built in step #1 into place.
  4. Delete (or archive) the existing-file from step #2.

The advantage of this procedure (which should be very well-documented) is that it will easily survive a crash and it can easily be recovered-from in the event of a crash.   (In fact, the program could do it automatically when it is re-run.)

“Ka-ka occurs,” and disk-space is plentiful and cheap.

Replies are listed 'Best First'.
Re^2: Help in read and write to file at a same time in same file.
by jpl (Monk) on Apr 04, 2011 at 18:08 UTC

    Perhaps this could be accomplished with yet another perlrun option, maybe -b (for backup). In conjunction with -i (whose behavior it would modify), we could demand that both have non-empty extensions, and further, that no two of the three names reference the same file, thereby defending against foot-shooting behavior like -i* or -b./* (for which silently deleting the "copy" might delete the original). It would then be safe to do largely as specified, after step 0, making a copy of the original in the -b extension. This keeps a backup of the original after the dust settles, much as -i does now, but also preserves the original, which won't be replaced by the -i version until it has been completely processed and closed.