I took the freedom to slightly simplify your spec, using a lookup table. The output should be what I suppose you want, i.e. replace all occurrences of c1 etc. with c1 d1 etc.:

#!/usr/bin/perl use strict; use warnings; my $fname_A = "file_A.txt"; my $fname_B = "file_B.txt"; my $fname_B_out = "file_B_out.txt"; my %subst; # lookup table open (my $data_fh, "<", $fname_A) or die "Couldn't open '$fname_A': $! +"; while (<$data_fh>) { chomp; my ($find, $add) = (split /\t/)[2,3]; $subst{$find} = $add; # print "$find => $add\n"; # debug } my $search = join "|", map quotemeta, keys %subst; open (my $in_fh, "<", $fname_B) or die "Couldn't open '$fname_B': + $!"; open (my $out_fh, ">", $fname_B_out) or die "Couldn't open '$fname_B_o +ut' for writing: $!"; while (my $line = <$in_fh>) { $line =~ s/($search)/$1 $subst{$1}/g; print $out_fh $line; }

The output might not be what you want in case the search strings aren't unique (because of the lookup hash), or if the substitutions aren't independent, such as when c1 => c2 in the first run through the file, c2 => d2 in the second run, etc. (because of doing it all in one go).


In reply to Re: Get data from a file to search and replace within a second file by almut
in thread Get data from a file to search and replace within a second file by biscardi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.