Hm, how about a hash per file and combine them on write?
use strict;
use warnings;
open FILE1, '<', 'file1.txt' or die ($!);
open FILE2, '<', 'file2.txt' or die ($!);
#- my %file1 = map { split '\|', $_ } <FILE1>;
my %file1 = map { chomp && s/\|$//g && split '\|', $_, 2 } <FILE1>;
#- my %file2 = map { split '\|', $_ } <FILE2>;
my %file2 = map { chomp && s/\|$//g && split '\|', $_, 2 } <FILE2>;
## we now have A1=>'dog' in one hash, and A1=>'Fido' in the other
close FILE1;
close FILE2;
open FILE3, '>', 'file3.txt' or die ($!);
for (sort keys %file1) {
print FILE3 join('|',$_,$file1{$_},$file2{$_}),'|',"\n";
}
close FILE3;
untested
Simply put, create a hash "map" of each file, then find where the keys intersect and print out the result.
Caveats:
- If there is no key in %file1, you won't get a result
- If there is no key in %file2, you'll get a warning about printing an undefined value.
- this makes assumptions about file formats
- Update:Files that are not well-formed will cause problems -- for this and other reasons, there needs to be better error-checking.
None of those are unconquerable, but are some things to consider if you're taking the idea for production code.
Update: modified the code based on thread below. Comments '#-' are old lines. A better thing to do than cheat with the file slurp might be something like:
my %file1;
while (<FILE1>) {
chomp; s/\|[\s]*$//;
my ($key, $val) = split '\|', $_, 2;
$file1{$key} = $val;
}
Of course, that's not nearly as fun...
The Eightfold Path: 'use warnings;', 'use strict;', 'use diagnostics;', perltidy, CGI or CGI::Simple, try the CPAN first, big modules and small scripts, test first.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.