open A, '<', 'fileA' or die "Cannot open 'fileA' $!"; my %lines; while ( ) { $lines{ $. } = () if /X/; } close A; open B, '<', 'fileB' or die "Cannot open 'fileB' $!"; my $count; while ( ) { s/(Y)/ exists $lines{ ++$count } ? 'Z' : $1 /eg; print; # updated to print lines } close B;