in reply to replacing in file
In the first code example, all you're doing is modifying the contents of $_ in the while loop, and then not bothering to do anything with it. In the second example...
open (OUTFILE, "<$dirContent");
You just opened your "out file" for reading. You wanted...
open (OUTFILE, ">$dirContent");
Worse still... You're opening the same file twice! You have two choices for what you want to do... Either open the original file for reading, and a new one for writing, then rename the new to the old when you're done, or better still, do this all from the command line (which will basically do the same thing under the hood.
perl -p -i.bak -e '/oldstring/newstring/'
Having to write a whole new file may seem unfortunate and inefficient, but you don't really have much choice. A file is a contiguous block of bytes, and if you grow or shrink a piece of it, you basically have to shift all the following pieces around, or rewrite the whole file. The only way around rewriting the whole file is to have a file of fixed record lenghts, or to store modification information at the end of the file, and have a very dynamic, on the fly type of data extraction occuring. The latter is how a lot of text editors work, recording lots of small changes at the end of the file, and every now and again performing a monolithic clean up and synchronization.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: replacing in file
by jc23 (Acolyte) on Aug 01, 2003 at 17:57 UTC | |
by sgifford (Prior) on Aug 01, 2003 at 18:13 UTC | |
by skyknight (Hermit) on Aug 01, 2003 at 18:16 UTC |