Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I have two files of double quoted values with a key in common, which I merge into a new file with redundant values removed.
dataa.txt
"state","location","name","school"
"Connecticut","New Haven","Jones, Jenny","Yale University"
"Massachusetts","Boston","Jones, James","Harvard University"
"New York","Ithaca","Smith, John","Cornell University"
"New York","New York","Williams, David","Columbia University"
datab.txt
"name","birth","birthplace"
"Jones, James","1954","Springfield"
"Jones, Jenny","1950","Middletown"
"Smith, John","1953","Albany"
"Williams, David","1954","Pittsfield"
resulting in datac.txt
My code is as follows:
use strict; use warnings; use Text::CSV; use Data::Dumper; my $csv = Text::CSV->new ({ quote_char => '"', escape_char => '"', sep_char => ',', eol => $\, always_quote => 1, quote_space => 1, quote_null => 1, binary => 0, keep_meta_info => 1, allow_loose_quotes => 0, allow_loose_escapes => 0, allow_whitespace => 0, blank_is_undef => 0, empty_is_undef => 0, verbatim => 0, auto_diag => 0, }); open (OUTPUT,'>datac.txt') or die $!; my (%hash1); my $file1 = 'dataa.txt'; open (CSV1,"<",$file1) or die $!; while (<CSV1>) { if ($csv->parse($_)) { my @fields1 = $csv->fields(); my $key1 = $fields1[2]; splice(@fields1,2,1); my $line1 = join ( '^' , @fields1); %hash1 = ($key1 => $line1); } else { my $err = $csv->error_input; print "Failed to parse line: $err"; } my $file2 = 'datab.txt'; open (CSV2,"<",$file2) or die $!; while (<CSV2>) { if ($csv->parse($_)) { my @fields2 = $csv->fields(); my $key2 = $fields2[0]; splice(@fields2,0,1); my $line2 = join ( '^' , @fields2); my $new = (); if (exists $hash1{$key2}) { my $new = join ('^' , $key2 , $hash1{$key2} , $line2); print OUTPUT $new,"\n"; } } else { my $err = $csv->error_input; print "Failed to parse line: $err"; } } } close CSV1; close CSV2;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Need doubled quoted values
by ikegami (Patriarch) on Mar 02, 2015 at 02:22 UTC | |
|
Re: Need doubled quoted values
by Tux (Canon) on Mar 02, 2015 at 09:11 UTC | |
by Anonymous Monk on Mar 02, 2015 at 09:55 UTC | |
by Tux (Canon) on Mar 02, 2015 at 10:53 UTC | |
|
Re: Need doubled quoted values
by Anonymous Monk on Mar 02, 2015 at 01:24 UTC | |
by Anonymous Monk on Mar 02, 2015 at 01:29 UTC | |
by LanX (Saint) on Mar 02, 2015 at 02:11 UTC | |
by AnomalousMonk (Archbishop) on Mar 02, 2015 at 03:52 UTC | |
by LanX (Saint) on Mar 02, 2015 at 04:10 UTC |