in reply to 2 Hash Tables, 4 Keys...what to do?
If the input files are sorted (or if you use an external tool to sort them before running the Perl script), a very memory-efficient algorithm can be used:
my ($f1_k1, $f1_k2); my ($f2_k1, $f2_k2); my $f1_line; my $f2_line; my $regexp = qr/^((\w+(?:\s+\w+){3})(?:\s+\w+){3}(.*)/; for (;;) { # Read from FILE1 if appropriate. if (not defined $f1_line) { $f1_line = <FILE1>; last unless defined $f1_line; # Extract the keys for comparison. ($f1_k1, $f1_k2) = $f1_line =~ $regexp; # Make sure the regexp matched. if (not defined $f1_k1) { undef $f1_line; next; } } # Read from FILE2 if appropriate. if (not defined $f2_line) { $f2_line = <FILE2>; last unless defined $f2_line; # Extract the keys for comparison. ($f2_k2, $f1_k2) = $f2_line =~ $regexp; # Make sure the regexp matched. if (not defined $f2_k1) { undef $f2_line; next; } } # Do the comparisons. my $cmp = $f1_k1 cmp $f2_k2; if ($cmp == 0) { print("Key 1 match:\n"); print("$f1_line\n"); print("$f2_line\n"); if ($f1_k2 eq $f2_k2) { print("...and key 2 matches.\n"); } else { print("...but key 2 doesn't match!\n"); } # Only read from one file in case of duplicate keys. undef $f2_line; } # Need to read from FILE1. undef $f1_line if $cmp < 0; # Need to read from FILE2. undef $f2_line if $cmp > 0; }
(The code isn't tested, but the idea is sound.)
|
|---|