Perl (Scripting) - Replace values in a file

by
Jeremy Canfield |
Updated: June 15 2021
| Perl (Scripting) articles
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.
my @fruit;
if (open FH, "<", "foo.txt") {
@fruit = <FH>;
close FH;
}
else {
print "failed to open foo.txt \n";
exit 1;
}
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.
if (open FH, ">", "foo.txt") {
foreach my $line (@fruit) {
print FH "$line";
}
close FH;
}
else {
print "failed to open foo.txt \n";
exit 1;
}
Did you find this article helpful?
If so, consider buying me a coffee over at