The first way is to open the file for read-only, open a temp file for output, read line by line through the input file while writing line by line to the temp file. Then when you get to the point where you want to add something, write it to the temp file too. Then continue reading from the input file and writing line by line to the output file until the end of file is reached. Close both files. Rename the temp file so that it replaces the original file. Done.
The other common method is using Tie::File. This module allows you to treat the file as an array. And as you probably know (maybe), you can insert items into the middle of an array by using splice. You can also push, pop, shift, and unshift an array. And, you can modify the contents of any of the array's existing elements. As you do this, all the grunt work of temp files, etc., goes on behind the scenes so you don't have to worry about it.
The reason that you cannot write (easily) to the middle of a file is that a file is a single long contiguous string written to a storage device. If you write to the middle, you overwrite what's already there; the OS doesn't have any idea how to insert, just overwrite. Also, files themselves don't have any concept of lines; that's a level of abstraction that Perl offers you for convenience. This is an oversimplification, but essentially sufficient to paint the picture.
Dave
In reply to Re: How Do I Add text to certain parts of the file?
by davido
in thread How Do I Add text to certain parts of the file?
by EchoAngel
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |