I'm pretty new to perl and I'm working on something where I need to update a file by appending data as well as deleting data that may already be in the file. I was wondering what the easiest way to do this would be?
Since you want to delete existing entries as well as add new ones, the easiest way is probably to read the whole file into an array, process the array to add and delete records, and then rewrite the array to the file.
Tracy Dryden
tracy@bydisn.com
Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
Reading the whole file into an array is definitely the easiest solution, but if you have a *LARGE* file, that might be a problem if you don't have a lot of memory on that machine. Alternatively you could
* open your input file for reading - with the "<" operator
* open an output file for writing - with the ">" operator
1. read your input file, line by line
- if the line is good and you want to keep it,
then write the line to the output file
- if the line is bad and you don't want to keep it,
then do NOT write the line to the output file
2. after the input file has been processed, close both the input file *AND* the output file, and then open the output file with the ">>" append operator. Then write whatever lines you want to append to the same output file.
3. You now have an output file that contains everything you want. If you want, you can rename that to the original input file - if you want to do this, I'd recommend using the File::Copy module - it makes moving or renaming a file very easy.
Hope this helps.
Hardy Merrill
Mission Critical Linux, Inc.
True, that's a good way to handle a large file. But you really don't need step 2 to append records. After you read and (possibly) write the existing records, just write the new records.
Tracy Dryden
tracy@bydisn.com
Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.