[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] search and replace a specific line in a file.



>Hi,
>
>I am writing a CGI that searches a flat file for a line that matches a
>specified string.  What I want to do when I find the line is to manipulate
>some of the contents and then write the line back to the file at the same 
>line number.  I am able to do everything except for the print to the file
>at the right spot (it just appends to the file).  I have the Camel book
>and the Llama book and I can't seem to figure out how to print to a 
>specific line in the file.  I know about the "$." variable that holds the 
>current input line number and that "$_" contains the input line contents,
>but how do I get "print" to print $string to OUTPUTFILE at "$." ? 

Try this:

open (OUT, ">flatfile.temp");
open (IN, "flatfile");

while (<IN>){
if (/f/){                             #finds the string you want to replace
print OUT "substitution string\n";    #prints the replacement
}else{
print OUT $_;
}
}
close (IN);
close (OUT);

open (IN, "flatfile.temp");
open (OUT, ">flatfile");

while (<IN>){
print OUT $_;
}


# Morten Pihl
# mpihl@inet.uni-c.dk