Hi All.

I just received this great piece of code below from a friend. It writes a line to to a specific place in an external file. Problem is each time it runs it adds another line just under the former line. Would anyone know how to modify this code to "replace" the old line with the new, rather than just keep adding new lines? Any advice would be deeply appreciated! Thanks!

Here is the code:
#!/usr/local/bin/perl use strict; use CGI ':standard'; print "Content-type: text/html\n\n"; my @array; # this opens the original file and sets up the # external file as an array open (FILE,"external_file.txt"); @array = <FILE>; close(FILE); # initializes loop count at 0 my $count = 0; #loops through the array (used to be the external # file) foreach (@array) { # the number (3 in his case) corresponds to the # line number where you want to add the #statement in quotation marks if ($count == 3) { #adds the statement in parenthesis to the array #(file) using the concatenation operator (the #period) $_ = $_ . "my newline goes here\n"; #use this line if you want to add a space before #the newline # $_ = $_ . "\nmy newline goes here\n"; #this prints the entire array (with the line #added) to a temporary file open (FILE,">>external.txt"); print FILE @array; close (FILE); #this renames the temporary file to the original #file name but with new line added rename ("external.txt","external_file.txt"); exit; } #endif #loop counter $count++; } #endforeach # exits the program just in case there are less # than the specified number of lines in # the original external file,if ($count == x) exit;

edited: Tue Oct 15 17:33:03 2002 by jeffa - code tags s/<br>//g


In reply to Replace a line with a new one by Donnie

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.