http://qs321.pair.com?node_id=873610


in reply to find & replace a string in perl

replacing string with a comment(#) at start of that line

That is not as easy as you think. If you want to replace a line then you must replace every character in it. When you look at a text file in an editor like Notepad or vi(1) then it is showing a visual representation - the file is not really like that. For example:
abc defg hij
is really like this:
abc\ndefg\nhij\n
The detail varies between operating systems, but UNIX and Windows are similar. So, to replace a line with a comment you would have to:
1. Open the file for read and write
2. Read the file until you find the line you need
3. Move the current file position backwards to the start of the line you just read, using seek.
4. Overwrite each character with a '#' - no more and no less than the original line length.

It is not worth the effort! Instead it is easier to:
1. Open the original file for read
2. Open a new file for write
3. In a loop, read each record, then decide if it is to be written to the new file.
4. Write the record, or not, then read the next record, and so on until end-of-file.