Perl's approach to reading and writting to the same file is to store the current file into an array or a temporary file, to update the array or temporary file, and to then replace the original file with the updated array or temporary file. I typically prefer to store the current file in an array instead of a temporary file.
Array
my $file = "example.txt";
# Open the file for reading
open(IN, "<", $file) or die "Cannot open $file $! \n";
# Load the content of the file into an array
my @array = <IN>;
# Close the file
close IN;
# Open the file for writing
open(OUT, ">", $file) or die "Cannot open $file $! \n";
# Loop through each line in @array
foreach my $line (@array) {
# THIS IS WHERE YOU WOULD MAKE YOUR MODIFICATIONS TO $line
# THIS IS JUST AN EXAMPLE OF REPLACING "old" WITH "new"
$line =~ s|old|new|;
# Write each line in the array to the file
print OUT $line;
}
# Close the file
close OUT;
Temporary file
my $file = "example.txt";
# Open the original file
open(IN, "<", $file) or die "Cannot open $file $! \n";
# Create a tmp file
open(OUT, ">", "${file}.tmp") or die "Cannot create $file.tmp $! \n";
# Loop through each line in the original file
while (my $line = <IN>) {
# THIS IS WHERE YOU WOULD MAKE YOUR MODIFICATIONS TO $line
# THIS IS JUST AN EXAMPLE OF REPLACING "OLD" WITH "NEW"
$line =~ s|old|new|;
# Write each line to the tmp file
print OUT $line;
}
# Close both files
close IN;
close OUT;
# Delete the original file
unlink($file);
# Rename the tmp file to have the original file name
rename("${file}.tmp", $file);