Edit Flat file with perl
I have a flat file(tabbed text) that I'm able to pull data from an split into values and display in a browser using perl.
What I need to do now id be able to modify a line in the flat file. Each entry has a unique id number. How would I go about setting this up.
I can handle getting the data for the record to be edited and into a form. But beyond that I'm lost.
Does it involve pulling all the data from the file changing it and then writing is all back? Could some one provide a little sample code of how to do this just to get me started.
Thanks,
spragueg
Thanks
G
Wil posted this at 13:16 — 9th September 2002.
They have: 601 posts
Joined: Nov 2001
Yes, I can guide you and provide sample code, but firstly, can you supply us with sample data? Can you give me a snapshop of the file? And also, what part of the file (which column) would you like to modify?
- wil
ROB posted this at 15:21 — 9th September 2002.
They have: 447 posts
Joined: Oct 1999
quick sample
open(MYFILE, 'path/to/myfile') || die();
my @lines = <MYFILE>;
close(MYFILE);
open(MYFILE, '>path/to/myfile') || die();
foreach(@lines) {
chomp;
# split the line into column data
my ($id, $fname, $lname, $moredata) = split(/\t/);
if($id == $idYouWantToChange) {
# do stuff with the line here
}
# write the line back to file
print MYFILE "$id\t$fname\t$lname\t$moredata\n";
}
close MYFILE;
spragueg posted this at 05:29 — 17th September 2002.
They have: 23 posts
Joined: Jan 2001
Ok That's what I thought however I am troubled by the writing it back part. Wouldn't MYFILE contain the original file contents. but you're showing only writing back the one line. Wouldn't I have to replace the current file in @lines with the new data and then put the @lines back into MYFILE? Then write the file?
Thanks
G
spragueg posted this at 05:46 — 17th September 2002.
They have: 23 posts
Joined: Jan 2001
Nevermind, I didn't get it when I first responded. I see the chomp; thing now. I like it. Exactly what I'm looking for!
Thanks much,
Graham
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.