in reply to Compare 3 files and print matches in Perl
It's generally good form to indicate if you've Crossposted to Stack Overflow and Unix & Linux Stack Exchange to prevent duplication of effort.
The answer I posted on Stack Overflow was:
#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; #read file1 into a hash - but invert is it's value => key instead: # 'CKEIFJ' => 'cmr03lsp', # etc. open( my $file1, '<', "file1.txt" ) or die $!; my %file1_content = map { reverse split } <$file1>; close($file1); print Dumper \%file1_content; #read file 2 - read keys, store the values. #split _2_ fields, so we keep both numbers as a substring: #e.g.: # 'cmr03lsp' => '60 70 #', open( my $file2, '<', "file2.txt" ) or die $!; my %file2_content = map { split( " ", $_, 2 ) } <$file2>; close($file2); print Dumper \%file2_content; #then iterate file 3, checking if: #file1 has a matching 'key' (but inverted - as a value) #file2 has a cross reference. open( my $file3, '<', "file3.txt" ) or die $!; while ( my $line = <$file3> ) { chomp $line; if ( $file1_content{$line} and $file2_content{ $file1_content{$line} } ) { print "$file1_content{$line} $line $file2_content{$file1_con +tent{$line}}"; } } close($file3);
Which prints (aside from Dumper diag content):
fji01dde AIDJFMGKG 25 30 cmr03lsp CKEIFJ 60 70
as requested
|
|---|