With flat files, you have a couple of options:
- You can open the file for appending. ...but then you will write at the end of the file. And if you use seek and tell to write elsewhere, then you overwrite what's already there.
- You can open the file for writing. ...but then you obliterate the entire contents of the existing file.
Neither of these outcomes are what you want. For that reason, you have to implement one of several more appropriate strategies:
- You can open the file for reading, open a temp file for writing, and line by line read through the file and write it back out to the tempfile. When you arrive at the position where you want to insert data, write out that inserted data, and then continue writing out the remainder of the file's contents until the temp file contains an exact copy of the master file plus the inserted line. Then close both files and use rename to rename the tempfile over the master file's name. This approach doesn't scale well if you have lots of inserts to be doing and the file becomes quite large.
- You can use Tie::File to treat the file like an array, and as merlyn stated, "splice to your heart's content". This approach also doesn't scale well if there are lots of inserts. But if your file really isn't going to grow terribly large, and you're not really concerned with speed, this is a very convenient and simple approach.
- Another approach is to always just append, but when you do so, append in the form of "employee name: comment". Then when you read the file back in, there will be multiple comments on a given employee name, and the comments may be interspersed in multiple places throughout the file. That's not a problem if you retrieve the employee name into a hash key whos value is a reference to an anonymous array containing all of the comments. You just scan through the file and find all of the comments prefixed with a particular employee's name. This again doesn't scale real well, but at least for insertion is faster than the previous two methods. And even if the file gets pretty big, it shouldn't take terribly long to scan through it for all of the comments attributed to a particular employee.
- The most scalable solution would be to adopt a database approach. And for simplicity in this respect, you might consider DBI along with DBD::SQLite. DBD::SQLite is a great little database implementation encased in a single module. It's easy to install, and not as intimidating as installing a database with a daemon. With this solution INSERTS won't be as inefficient as they are with flat files, and SELECTS (queries) will be very fast.
I hope this gives you some ideas to work with.