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

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



Ernesto Gonzalez <Gonzalez@molbio.mgh.harvard.edu> wrote:
>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 "$." ?

A file is one lineair string of characters in which you cannot insert or
delete. If the file is not too big, you can do the following:

- open the file for read
- read all lines in a list
- close the file
- change the line you want
- open the same file for write
- write all the lines in the list to the file

If the file is big, open another file and write all unchanged lines and the
changed line to it, then delete the old file and rename the new to the old
name.

Maurice