Ok, first get the line numbers,
my %line;
{
open my $fhA, '<', 'A' or die $!;
while (<$fhA>) {
$line{$.} = undef if /$X/;
}
}
The $. variable counts line numbers.
Now open up file B and do the substitution if $line{$.} exists. Keep all the lines of the revised file and write them back when done.
use Fcntl qw/:flock/;
{
my @file;
open my $fhB, '+<', 'B' or die $!;
flock $fhB, LOCK_EX or die $!;
while (<$fhB>) {
s/$Y/$Z/ if exists $line{$.};
push @file, $_;
}
truncate $fhB, 0 or die $!; # set up to overwrite file
print $fhB @file;
}
That does it.
I do wonder if your requirement represents a good design. It seems to suppose the the two files will always be in synch. It could be trouble if whatever creates them doesn't ensure that at every moment.
Added: As an alternative, use Tie::File for file B.
use Tie::File;
tie my @file, 'Tie::File', 'B' or die $!;
{
open my $fhA, '<', 'A' or die $!;
while (<$fhA>) {
$file[$. - 1] =~ s/$Y/$Z/ if /$X/;
}
}
That has the advantages of brevity and low memory use.
|