First of all, you should always use strict and use warnings at the top of each program. This way, you will be shown simple errors that you would otherwise have missed.
Secondly, you should use the names of lexical files, the three-parameter form of open and always check the status of each call to open .
To solve the problem, you should simply search for the line containing the accepted by prefix, and then append the lines to the line you found until you see a complete line match. It is also better to use explicit [^.]+ Than not greedy .*? to avoid backtracking.
Note that you must restore the open file that I commented out and delete the destination $file , since I wrote the program this way for testing purposes.
This solution will have a problem if accepted by is split into multiple lines. If you expect this, then you will need to code something a little different.
use strict; use warnings;
Output
accepted by: Tim accepted by: The Financial Director
source share