in reply to This has me stumped, pattern matching, 2 files
Ok, first get the line numbers,
The $. variable counts line numbers.my %line; { open my $fhA, '<', 'A' or die $!; while (<$fhA>) { $line{$.} = undef if /$X/; } }
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.
That does it.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; }
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.
That has the advantages of brevity and low memory use.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/; } }
After Compline,
Zaxo
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: This has me stumped, pattern matching, 2 files
by ikegami (Patriarch) on Nov 21, 2006 at 07:44 UTC | |
by tsk1979 (Scribe) on Nov 21, 2006 at 08:30 UTC | |
by ikegami (Patriarch) on Nov 21, 2006 at 15:54 UTC | |
|
Re^2: This has me stumped, pattern matching, 2 files
by tsk1979 (Scribe) on Nov 21, 2006 at 06:54 UTC | |
by Zaxo (Archbishop) on Nov 21, 2006 at 07:03 UTC |