If you have enough memory, use a hash. If the characters do not occur several times in the input1.txt file (i.e., if AB is in the file, AX not), then the following should work:
#!/usr/bin/perl use warnings; use strict; my %hash; open my $F1, '<', 'input1.txt' or die $!; while (<$F1>) { my @values = split / /; @hash{@values} = reverse @values; } close $F1; open my $F2, '<', 'input2.txt' or die $!; while (<$F2>) { my @values = split / /; my $value = $hash{$values[0]}; if ($value and $value eq $values[1]) { print "Matches: $_"; } else { print "Does not match: $_"; } } close $F2;
Update:
For repeated values, I would use a hash of hashes. Just sort the characters, the first of which will be the key in the large hash, the second will be the key in the subhash:
#!/usr/bin/perl use warnings; use strict; my %hash; open my $IN1, '<', 'input1.txt' or die $!; while (<$IN1>) { my @values = sort split; undef $hash{$values[0]}{$values[1]}; } close $IN1; open my $IN2, '<', 'input2.txt' or die $!; while (<$IN2>) { chomp; my @values = sort split; if (exists $hash{$values[0]}{$values[1]}) { print "$_ matches\n"; } else { print "$_ doesn't match\n"; } } close $IN2;
source share