use Text::CSV_XS (); my %data; parse_ssn_file( "file1.txt", \%data ); parse_salary_file( "file2.txt", \%data ); my $csv = Text::CSV_XS->new(); foreach my $cur ( sort keys %data ) { $csv->combine( $cur, @{ $data{$cur} }{qw( ssn file salary zip )} ); print $csv->string, "\n" } exit 0; sub parse_ssn_file { my( $file, $data ) = @_; local( *CUR ); open( CUR, $file ) or die "Can't open $file: $!\n"; scalar <CUR>; # discard header my $csv = Text::CSV_XS->new( ); while( <CUR> ) { $csv->parse( $_ ); my @cur = $csv->fields(); $data->{ $cur[0] }->{ssn} = $cur[1]; $data->{ $cur[0] }->{file} = $cur[2]; } return } sub parse_salary_file { my( $file, $data ) = @_; local( *CUR ); open( CUR, $file ) or die "Can't open $file: $!\n"; scalar <CUR>; # discard header my $csv = Text::CSV_XS->new( ); while( <CUR> ) { $csv->parse( $_ ); my @cur = $csv->fields(); $data->{ $cur[0] }->{salary} = $cur[1]; $data->{ $cur[0] }->{zip} = $cur[2]; } return } __END__
file1.txt Name,SSN,File "Doe, John",123456789,3447 "Flinstone, Fred",000000302,1234 file2.txt Name,Salary,ZIP "Flinstone, Fred",34500,90210 "Doe, John",50000,10003 Output: "Doe, John",123456789,3447,50000,10003 "Flinstone, Fred",000000302,1234,34500,90210

Update: D'oh, might help if I answered the whole question. :/ If you want to catch exceptions then you'd want to pick whatever file is going to be canonical and parse it first. Have all the other parse_foo_file routines first do an exists $data->{$cur} to check whether it's a valid, existing name before inserting the data. If it's not, have an open log file (open( REJ, ">$filename.rej" ) or die $!) that you can print the rejected entries into.


In reply to Re: Merging files by Fletch
in thread Merging files by ellem

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.