Donnie has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Replace a line with a new one
by Aristotle (Chancellor) on Oct 15, 2002 at 09:05 UTC | |
|
Re: Replace a line with a new one
by nothingmuch (Priest) on Oct 14, 2002 at 21:03 UTC | |
by Donnie (Acolyte) on Oct 14, 2002 at 22:21 UTC | |
by nothingmuch (Priest) on Oct 14, 2002 at 22:39 UTC | |
|
Re: Replace a line with a new one
by Zaxo (Archbishop) on Oct 14, 2002 at 20:41 UTC | |
|
Re: Replace a line with a new one
by kabel (Chaplain) on Oct 14, 2002 at 21:02 UTC | |
|
Re: Replace a line with a new one
by Steve_p (Priest) on Oct 14, 2002 at 20:41 UTC | |
by Donnie (Acolyte) on Oct 14, 2002 at 21:30 UTC |