Gossamer Forum
Home : General : Perl Programming :

Adding new lines from the top

Quote Reply
Adding new lines from the top
I am writing a news script in which I would like to have new stories on the top. What is required is that a SSI include will pull the info from a txt file and display it. However, when I add new stories, it always append to the bottom of the text file therefore, the new stories will appear always at the bottom. How can I make it print on the first line and bring the other lines from the top down?

------------------
http://www.techdevelopers.com
ASP, HTML, CGI, Flash, and more!

HPCalc.com - English
Official HP Calculator Site
http://www.hpcalc.com/english

Quote Reply
Re: Adding new lines from the top In reply to
Perl only allows you to append or overwrite a file. So to add a line at the top of the file you have to read the file into an array or variable, overwrite the file with the line you want to add, and then append the array or variable onto the file. This has definitely been discussed on this board before, and sample code has been posted. Use the Search function to see if you can find anything. If you can't, post again and someone will post some code.

adam

____________________________________
Perl & PHP Coding -> adam@iewebs.com
Quote Reply
Re: Adding new lines from the top In reply to
I did a search on the forum, but got no good revelant hits. So I tried viewing the posts from the last year, but still couldn't find any in particular. Can someone help me find it?
Quote Reply
Re: Adding new lines from the top In reply to
One way would be to:

1. Open old file for reading. Read old file into variable (e.g., $old_file).
2. Create a temp file for writing.
3. Write the new lines to the temp file.
4. Then write (append) old lines to the temp file.
5. Delete old file.
6. Rename temp file, old file.

Dan Smile
Quote Reply
Re: Adding new lines from the top In reply to
Yea, I've got it now. Thanks anyway Dan. I didn't want to create a temp file each time, so I just read the file into an array, erase the file contents, printed the line I wanted first, then ran a foreach loop which pasted the old contents after the new info. Thanks anyway.
Quote Reply
Re: Adding new lines from the top In reply to
You have probably chosen the best alternative if this text file has multiple lined entries. If you are using single-line entries (i.e. a delimitered flat file) you could always just append to the file in the normal fashion and then when reading from it, insert the file into an array and run the 'reverse' function on it.
ex.
open(BLAH, "your_flat_file") | | die $!;
@stuff = <BLAH>;
close(BLAH);
@output = reverse(@stuff);

------------------
$blah='82:84:70:77';
print chr($_) foreach (split/:/,$blah);

[This message has been edited by GClemmons (edited October 22, 1999).]