note
haukex
<p>You can use the following pattern to slurp and spew a file:</p>
<c>
use warnings;
use strict;
my @files = <Test*_Copy>;
for my $modfile (@files) {
# read
open my $ifh, '<', $modfile or die "$modfile: $!";
my $data = do { local $/; <$ifh> }; # slurp
close $ifh;
# modify
$data =~ s/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/smg;
# write
open my $ofh, '>', $modfile or die "$modfile: $!";
print $ofh $data;
close $ofh;
}
</c>
<p>(Slurping can also be shortened to <c>my $data = do { open my $fh, '<', $modfile or die $!; local $/; <$fh> };</c>, though that's a bit less readable if you're not used to it).</p>
<p>Or you can use a nice module like [mod://Path::Class] or [mod://Path::Tiny]:</p>
<c>
use warnings;
use strict;
use Path::Tiny;
my @files = path(".")->children(qr/^Test.*_Copy$/);
for my $modfile (@files) {
$modfile->edit(sub {
s/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/smg;
});
}
</c>
<p>Or you can use a oneliner ([id://1216313|see also] [doc://$^I]):</p>
<c>
perl -wMstrict -0777 -i -pe 's/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/smg' Test*_Copy
</c>
<p>Or you can use my module [mod://File::Replace] for atomic updates when the filesystem supports it:</p>
<c>
use warnings;
use strict;
use File::Replace 'replace3';
my @files = <Test*_Copy>;
for my $modfile (@files) {
my ($infh,$outfh,$repl) = replace3($modfile);
my $data = do { local $/; <$infh> };
$data =~ s/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/smg;
print $outfh $data;
$repl->finish;
}
</c>
<p>Or you can open the file in read-write mode, truncate it after reading, and then write it - though note I see this being done very rarely. (It's useful if you want to [doc://flock] the file while editing. That can be as simple as adding <c>use Fcntl qw/:flock/;</c> at the top of the code and <c>flock($fh, LOCK_EX) or die "flock $modfile: $!";</c> immediately after the [doc://open]. Keep in mind that <c>flock</c> locks are merely advisory, though!)</p>
<c>
use warnings;
use strict;
my @files = <Test*_Copy>;
for my $modfile (@files) {
open my $fh, '+<', $modfile or die "$modfile: $!";
my $data = do { local $/; <$fh> };
$data =~ s/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/smg;
seek $fh, 0, 0 or die $!;
truncate $fh, 0 or die $!;
print $fh $data;
close $fh;
}
</c>
<p>Note that [id://1206848|glob has several caveats], though as shown in this code it's ok.</p>
<p><small><i>Updates:</i> Added info on <c>flock</c> and <c>$^I</c>.</small></p>
11120512
11120512