in reply to Replace a line with a new one

Several problems arise from the code. The first - scalability - reading a whole file into an array is kinda asking for trouble, you might run out of memory, and it'll probably take a longer while.
Another is that you're opening the temporary file for appending. Assuming the file is new, this shouldn't matter to you, but if a file by that name exists, you just added the new text to it's end, instead of rewriting from scratch. See perlopentut for a tutorial on openning files.
Yet another, which directly confronts your problem, is that the readline operator does not remove the input record seperator ($/, which is usually "\n") from read lines.
reading a file which contains "foo\nbar\n" into an array will yield ("foo\n","bar\n").
When you join $_ with your string, it'll keep the line break you put in, making $_ contain two lines.
To get around that line break you need to use chop, which takes off the last character of a string, or chomp which only removes an occurance of $/ from a string.
I think the wisest approach would be something like this:
open (FILE,"external_file.txt"); open (TEMP,">external_file.txt.tmp"); my $i = 0; while (<FILE>){ # magical - puts every line in $_, until the end of fi +le is reached if ($i == 3){ # if $i is the 3rd line chomp $_; # remove the line break at the end of $_ $_ .= "my new line goes here\n"; # add the string } print TEMP $_; # print the line you just read to the temporary fil +e } continue { # performed at the end of every loop iteration $i++; } close FILE; close TEMP; unlink ("external_file.txt"); # incase rename does not clobber, delete + the original rename ("external_file.txt.tmp","external_file.txt");
-nuffin zz zZ Z Z #!perl

Replies are listed 'Best First'.
Re: Re: Replace a line with a new one
by Donnie (Acolyte) on Oct 14, 2002 at 22:21 UTC
    Thanks so much for the good advice.
    I just tried your code and it works well - however - it behaves the same as the original in that it just keeps adding another line every time it runs - instead of overwriting the previous line written. It appends another line right behind the previous one.
    The other code added a new line just under the previous line.
    Any further thoughts?
    Thanks again for responding.
      Ah, ok... I understood from the code that you are trying to join the strings, from the concatenation operator ^_^. I should make it a habit to make notice of the english...
      $_ = "my newline\n" if ($i == 3); print TEMP $_;
      hope this works...

      -nuffin zz zZ Z Z #!perl