in reply to Cleaner way of looping through a file and stripping only certain lines?

I'm curious as to how one would go about editing the file in place, i.e., not having to create a new outfile.

Open the file. Read the file into an array. Close the file. Open the same file for overwrite and write what you want back.

open(IN, '<', $ifile) or die "Couldn't open file: $!\n"; my @data = <IN>; close IN; open(OUT, '>', $ifile) or die "Couldn't open outfile: $!\n"; foreach my $line (@data) { ### Do what you want print OUT "$line"; }
UPDATE: Fixed some C&P errs

grep
XP matters not. Look at me. Judge me by my XP, do you?

  • Comment on Re: Cleaner way of looping through a file and stripping only certain lines?
  • Download Code

Replies are listed 'Best First'.
Re^2: Cleaner way of looping through a file and stripping only certain lines?
by throop (Chaplain) on Dec 08, 2006 at 17:14 UTC
    >>I'm curious as to how one would go about editing the file in place, i.e., not having to create a new outfile.
    >Open the file. Read the file into an array. Close the file. Open the same file for overwrite and write what you want back.

    This works, but isn't it inherently risky for cases where there's a power failure or other hiccup during processing — you corrupt your original?

    throop

      Yes it is. But so is any in-place edit.

      A safer answer would be to use File::Temp. You still have a problem with power failure but your window of problems is smaller.

      ## UNTESTED use File::Temp 'tempfile'; use File::Copy; my ($tmp_FH,$tmp_fn) = tempfile(); open(IN, '<', $ifile) or die "Couldn't open file: $!\n"; my @data = <IN>; close IN; foreach my $line (@data) { ### Do what you want print $tmp_FH "$line"; } copy($tmp_fn,$ifile);

      grep
      XP matters not. Look at me. Judge me by my XP, do you?

      The safer way to do this sort of thing is to write to a new file and then rename over the file you want to replace. This is what you do when handling mbox files for instance.

      The rename is an atomic operation. It's guaranteed to succeed completely or not at all (on Unix-like boxes), so you can never lose data as a result of a power failure.

      This is a similar trick to perl -i, but I think that does a rename of the original file and then writes back into the original file, which still leaves open the case that you could have bad (partially written) data in the original file on power failure.