Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: File handles in regular expressions

by Kenosis (Priest)
on Oct 19, 2012 at 07:04 UTC ( #999876=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: File handles in regular expressions
Select or Download Code
Re^2: File handles in regular expressions
by Lotus1 (Chaplain) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://999876]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (13)
As of 2014-10-01 15:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (29 votes), past polls