in reply to This has me stumped, pattern matching, 2 files

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

Replies are listed 'Best First'.
Re^2: This has me stumped, pattern matching, 2 files
by ikegami (Patriarch) on Nov 21, 2006 at 07:56 UTC

    You output to a third file. Let's fix that.

    my $file_a = '...'; my $file_b = '...'; my %lines; { open my $fh, '<', $file_a or die "Can't open index file \"$file_a\": $!\n"; while (<$fh>) { $lines{$.} = 1 if /X/; } } { # Immitate "perl -pi". local $^I = ''; local @ARGV = $file_b; my $count = 0; while (<>) { s/(Y)/ exists $lines{ ++$count } ? 'Z' : $1 /eg; print; } }

    Also fixed:

    • Used lexical variables instead of package variable whenever possible.
    • Removed the source line number from error messages likely caused by user error. By adding a descriptive name for the file in the error message — I used "index" since I'm not sure what the file is — the error message is easily locatable without the line number.