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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |