You can't read and write to the file at the same time like that. You're certainly free to use the same file handle, and that looks like that's what you meant to do with the open modes you chose. Just read in the whole file, then seek to the beginning, write out what you want to, and truncate it to the length of what you've written.
Example:
open(FILE, "+<$file");
my $temp;
while(<FILE>) {
$temp .= $_;
}
seek(FILE,0,0);
print FILE $temp;
truncate(FILE,tell(FILE));
close(FILE);
Of course, you'll want to add some dies to that.
If you're worried about memory usage, I'd suggest reading the file in one line at a time, writing out to a temp file one line at a time, then just moving the temp file over the original (don't forget to preserve permissions). |