in reply to Re: Edit Macintosh file, keeping resource fork
in thread Edit Macintosh file, keeping resource fork

Thanks for the tip!

The type of editing I want to do is a simple line-by-line

while (<IN>) { s/foo/bar/g; print OUT; }
type thingie. That code is written to make a copy as it edits (which is what I've always done).

How would I do that with in-place editing? Is it possible?

Replies are listed 'Best First'.
Re^3: Edit Macintosh file, keeping resource fork
by eieio (Pilgrim) on Feb 10, 2005 at 22:55 UTC
    If you are not increasing or decreasing the number of characters in the line, the following example may work:
    open( FILE, "+<", $fileName ) or die "can't open file: $!"; while( <FILE> ) { if( s/foo/bar/g ) { seek( FILE, -(length), 1 ) or die "can't seek: $!"; print FILE; } }

    Alternatively, you could read the entire file into a variable, perform your substitutions, seek to the beginning of the file, and write the contents of the variable to the file.

      Hmmm ... doesn't quite fit my situation. My edits will probably change the length of the lines, and the files are too big to load all at once.

      Is it possible for me to

      1. Open the file for in-place edits
      2. Open a temp file for output
      3. Read the file a line at a time, writing the edited output to the temp file
      4. Close the temp file and open it for read
      5. Read the temp file line by line, writing back to the original file (which is still open for in-place edits)
      ???

      Do I need to do something to truncate the original file before writing back to it, like setting its length to zero or something?

        I made this more complicated than it needs to be. On my Mac OS X system, if I open the file for reading, incrementally read the file and store the modified contents, close the file, reopen the file for writiing, and write the modfiied contents, the resource fork is preserved. I suppose you'll only run into trouble if you create a new file or copy the existing file in such a manner that the resource fork is lost.