You have to realize that files on disk aren't the same as the contents of those files in memory. When you do s/foo/bar/ while <IN> you are making a copy of the line of IN in memory, then doing the substitution-- and then throwing it away!
Your second example is opening the file in the wrong mode-- you really wanted to say open(OUTFILE, ">", "$dirContent"). I always think of that > as a funnel to pour stuff into the file. Using three-argument open when you explicitly want a read/write mode makes your code easier to read. (By the way, ,open(FILE, "<", $file) is the same as open(FILE, $file). And you may want to use open(args) or die($!) to check if you succeeded.)
Of course, you don't want to output into the file while you're still inputting from it. You can build up a scalar, then close infile, open outfile and print at the end, or you can make a temp file, then rename it to the name of the original file at the end, or whatever. But on my (Linux) system, opening the file for output erases it-- before you get a chance to read it in.
In reply to Re: replacing in file
by Anonymous Monk
in thread replacing in file
by jc23
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |