There are a few ways you can go about editing a line in place in a text file without using a temporary file.
One way would be to read in the entire file into memory, make your changes to the appropriate line in memory, and then write the entire file back out to disk. This would work fine for small files, but could be problematic for large files.
Another way would be to read in the file one line at a time, make your changes, and write the line back out. If you're only making changes to a single line, this would be much more efficient than reading the whole file into memory.
Here's a quick example of how you might do this:
#!/usr/bin/perl
use strict;
use warnings;
open my $in_fh, '<', 'input.txt' or die $!;
open my $out_fh, '>', 'output.txt' or die $!;
while ( my $line = <$in_fh> ) {
if ( $. == 10 ) {
# make your changes here
$line =~ s/foo/bar/g;
}
print $out_fh $line;
}
close $in_fh;
close $out_fh;
In this example, we're reading in the file one line at a time. We're keeping track of which line we're on with the $. variable. If we're on line 10, we make our changes and then write the line back out.
One thing to keep in mind with this approach is that you'll need to open the input and output files before the loop. That way, the filehandles will be available inside the loop.
You could also use the seek function to move around inside the file without reading the whole thing into memory. This would be more efficient if you only needed to make a few changes to specific lines.
For more information, see the following link:
https://www.perlmonks.org/?node_id=11574