Let's say I want to replace every occurrence of 12345 in file1 with the contents of file2. The following code works:
use strict;
use warnings;
local $/;
open my $fh, 'file1' or die "$!";
my $file1 = <$fh>;
close $fh;
open $fh, 'file2' or die "$!";
my $file2 = <$fh>;
close $fh;
my $file3 = $file1 =~ s/12345/$file2/gr;
open $fh, '>>', 'file3' or die "$!";
print $fh $file3;
close $fh;
I'm probably overthinking this but from a theoretical standpoint what would be the proper, efficient way to do this without causing a lot of copying in memory? Also, I'm new to Perl so feel free to point out anything here that goes against Perl best practices.
If you're writing out to a different file, and if the pattern doesn't span lines, you could read the file to modify one line at a time.
But reading the entire file into memory is also perfectly acceptable (and faster) unless you have concerns about the size of the file. And it's simpler if you want to write back to the same file.
Adding some whitespace makes of a huge improvement in readability (which @Miller did by editing your question).
But a module like File::Slurper can make it even cleaner.
use File::Slurper qw( read_text write_text );
my $to_insert_qfn = ...;
my $file_qfn = ...;
my $to_insert = read_text( $to_insert_qfn );
my $file = read_text( $file_qfn );
$file =~ s/12345/$to_insert/g;
write_text( $file_qfn, $file );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With