Gossamer Forum
Home : General : Perl Programming :

grabbing one line and putting it back again.

Quote Reply
grabbing one line and putting it back again.
I'm playing with some perl I/O for the time. Smile
I got this db file with some information on each line. Let me show you an example:

1|Link's 1 name|http://www.link1.com |Description 1
2|Link's 2 name|http://www.link2.com |Description 2
3|Link's 3 name|http://www.link3.com |Description 3

Now I want to grab one of the lines by searching for the number and display them. But if I want to change them and save them back into the same place I had them, how could I do that.

The only way I would know to do such thing is to remove the the line, edit it, and then save it to the bottom of the file. So I could grab link 1, change it, and add it below link 3. But the thing here is that I have this adding script. I can add more links to the file. But for each new add it gets a number greater than the last one. So if I have 3 links, it grabs the latest number(in this case 3) and adds 1(that would make 4 if my math is right).

This process would become totally ruined if I add link number 1 to the bottom. See my point of view?

While writing this I came up with a method, actually..but I don't think it will work.

Lets say I loaded the whole file into an array. With each line separated. Could I do something like running the whole array through a foreach loop and do something like this:

$line =~ s/Description 1/New Description 1/


I think that would work, but(horrible word!) I would again have a problem.
In my file I include a rating tag, and number of clicks(added when inserted). What if I had to links with the same number of clicks! Or In worst case, rating!

Anyone who want to help me with this? Somebody got a solution for my little problem?

I appreciate all help. Thank you.

- perlman

Last edited by:

perlman: Sep 28, 2003, 9:50 AM
Quote Reply
Re: [perlman] grabbing one line and putting it back again. In reply to
well, you could of course slurp the whole file into memory and do a rexexp, but I wouldn't recommend it for large files.

The easiest way to do this is to read from your source file and write to a temporary file during a while loop.

for example:
my $rec = 23;
my $new = "23|adlkf|asdkdkd\n";

open (IN, "mydb.db") or die $!;
open (OUT, ">mydb.db.temp") or die $!;
flock (OUT, 2);
while (my $line = <IN>) {
if ($line =~ /^$rec\|/) {
print OUT $new;
else {
print OUT $line;
close OUT;
close IN;
rename("mydb.db.temp", "mydb.db") or die $!;

Limecat is not pleased.