
japhy
Enthusiast
Jan 15, 2000, 9:27 AM
Post #6 of 6
(3487 views)
|
Re: writing a line above in a file
[In reply to]
|
Can't Post
|
|
Ah, well, in your case, you don't need to write to the top of the file. If you append, like shown below, you can still do what you wish: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> open LINKS, ">>links.txt" or die "can't append to links.txt: $!"; print LINKS "next link\n"; close LINKS; # then later, to read them, NEWEST FIRST open LINKS, "links.txt" or die "can't read links.txt: $!"; chomp, unshift @files, $_ while <LINKS>; close LINKS; </pre><HR></BLOCKQUOTE> This is a more efficient idea than: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> chomp(@files = <LINKS> ); @files = reverse(@files); # or chomp(@files = reverse(<LINKS> )); </pre><HR></BLOCKQUOTE> Because like I said in the previous post, these require a list of all the lines of the file to be built all at once, which can take a lot of memory for a big file. My solution uses the unshift() function, which places an element at the BEGINNING of an array, as opposed to push(), which puts the element at the end of the list. Don't be thrown by the while-loop looking kind of backwards: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> while (<LINKS> ) { chomp; unshift @files, $_; # or # chomp, unshift @files, $_; } # is the same as chomp, unshift @files, $_ while <LINKS>; </pre><HR></BLOCKQUOTE> For simple code structures, you can put while(), until(), and if() at the end of a statement. You CAN'T do this, though: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> print "hello" if $name eq "Jeff"; print "goodbye" else; </pre><HR></BLOCKQUOTE> That 'else' there isn't right... if you need if-else-elsif blocks, you have to do those in the regular style. Also, if you have a recent enough version of Perl, you can place for() or foreach() at the end of a statement: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> print "$_...\n" for reverse(1 .. 10); print "blast off!\n"; </pre><HR></BLOCKQUOTE> I think that's enough for now. I've got to leave SOMETHING for another answer. [This message has been edited by japhy (edited 01-15-2000).]
|