I have a file handler to a file and I’m looking for matches in the lines and replacing the match with a new line. Replacing the lines happen in a subroutine.
sub replace{
seek(FILE,0,0);
while(my $line= <FILE>){
if($line =~ m/SOMEMATCH/){
$line=~ s/SOMEMATCH/REPLACEMENT/;
print FILE $line;
}
}
}
When I print the file after calling &replace I find that the wrong line was changed so:
Line 1
Line 2
Line 3
SOMEMATCH
Line 4
Line 5
becomes:
Line 1
Line 2
Line 3
SOMEMATCH
REPLACEMENT
Line 5
What’s going on? How do I fix it?
I don’t think you can read in a text file and replace parts of it – in place – with strings that are longer or shorter and get the results you want. There has to be an overwriting of some data by the longer new string or a “hole” will be left if the string is shorter. If the strings happen to be the same length your logic still has a problem – replacing the string would require you to back up since you are past the string you want to replace after you have read it. Writing a replacement at that point should overwrite the next line since that is where the file “pointer” is currently set to ready to read the next line.
I think something like this is best done by having a separate output file. Read one, write the other, and if necessary, delete the first and rename the second.
Or you could read the entire file into an array, make your string replacements, close and reopen the file for over-writing, and write the array back to the file, and close the file.