http://www.perlmonks.org?node_id=999876


in reply to File handles in regular expressions

Hi, Vikas, and welcome to PerlMonks!

You've enclosed one loop within another, so you're attempting to compare the first $comp1 value against all elements of @var2, and so on. And tobyink's point about "if they match" is well made, so I suspect you want $comp1 eq $comp2.

Given this, consider the following:

use strict; use warnings; my %matchingLines; open my $fh1, '<', 'File1.txt' or die $!; chomp( my @file1Lines = <$fh1> ); close $fh1; open my $fh2, '<', 'File2.txt' or die $!; chomp( my @file2Lines = <$fh2> ); close $fh2; for my $file1Line (@file1Lines) { $matchingLines{"$file1Line\n"}++ if $file1Line ~~ @file2Lines; } open my $fh3, '>', 'FileA.txt' or die $!; print $fh3 $_ for keys %matchingLines; close $fh3;

If a line in @file1Lines is found in @file2Lines via the smart match operator (works as equality), it's added to the hash %matchingLines for later printing to a file (the hash is used to avoid the possibility of writing multiple instances of the same line to the file).

Hope this helps!

Update: Lotus1 correctly brought to my attention that I misunderstood the OP. Have revised the script.

Replies are listed 'Best First'.
Re^2: File handles in regular expressions
by Lotus1 (Vicar) on Oct 19, 2012 at 15:26 UTC

    Your solution only matches if the line at the same line number in both files is the same. The OP was attempting to match each line in file1 against each line in file2. For the files listed below only the first line is matched even though there are four lines that match.

    File1.txt: item1 item2 item3 item4 File2.txt: item1 abc item2 item3 item4 File3.txt: item1

      Wow! I certainly misunderstood the OP. Will strike/revise this. Thank you for pointing this out.