There are multiple ways to replace text in a file in Perl. Let's say example.txt contains the following lines of text.
apple
orange
grape
pineapple
I like to first store the content of the file in an array. In this example, the @fruit array will contain apple orange grape pineapple.
open(FH, "<", "/path/to/example.txt") or die "cannot open file $! \n";
my @fruit = <FH>;
close FH;
Then I use the map operator to update the array. In this example, "orange" is replace with "peach".
map { s/orange/peach/g } @fruit;
Then the file is overwritten to contain the values in the array.
my $file = "/path/to/file.txt";
open(FH, ">", "$file") or die "cannot open $file $! \n";
foreach my $line (@fruit) {
print FH "$line";
}
close FH;