Your code reads the entire INFILE2 for each line of INFILE.

I have re-written the code to help you get the logic right.

This code is fairly efficient (There is room for improvement, but it would increase complexity), and made more verbose and simplified.
See the discussion in Alternation vs. looping for multiple searches for improvement ideas.
Untested.

Assumes INFILE contents are smaller than INFILE2, AND small enough to fit into memory.

If this is not the case, you need to consider using a database.

#!/usr/bin/perl -w use strict; use warnings; my %subst; my $data = 'reference.txt'; open my $INFILE, '<', $data or die "cannot read $data: $!"; while(defined my $line = <$INFILE>) { chomp($line); my ($id, $description) = split /\t/, $line, 2; $subst{$id} = $description; } close $INFILE; my $data2 = 'readthisfile.txt'; open my $INFILE2, '<', $data2 or die "cannot read $data2: $!"; while(defined my $line2 = <$INFILE2>) { ## chomp($line2); Dont chomp - leave newline in for printing my $changes = 0; for my $id (keys %subst){ if ($line2 =~s/$id/$subst{$id}/g){ # This line was changed $changes++; } } print $line2 if $changes; #Prints only changed lines } close $INFILE2;

     Syntactic sugar causes cancer of the semicolon.        --Alan Perlis


In reply to Re: Search & Replace Across Two Files by NetWallah
in thread Search & Replace Across Two Files by sophix

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.