Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing data from a file

Status
Not open for further replies.

jae21

Technical User
Jul 13, 2001
6
US
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.
 
Thanks for the info. So I would need to open the file with over permission?

Also, are there any methods that delete an element from an
array and push down all the subscripts accordingly?
 
Yes, you would want to open the file, read it, close it, and open it again with > to overwrite it.

The splice command will do what you want with an array.
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 &quot;<&quot; operator
* open an output file for writing - with the &quot;>&quot; 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 &quot;>>&quot; 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.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top