Friday 15 August 2014

Perl: Compare Two CSV Files and Print out differences -


I'm a Noah in Perl and I have a hard time doing this. I have two single-columned CSV files, and I am trying to print the difference in one-third file.

  File 1: 123 124 125 126 File 2: 123 124 127 Expected Output: 125 126 127   

This is what I have so far received, which Not working:

  #! Use / usr / bin / perl strict; Use warnings; My $ sheet; My $ letter_2; My $ count1 = 0; My $ count2 = 0; My $ file1 = 'file1.csv'; My $ file2 = 'file2.csv'; My $ file_out = 'output.csv'; Open (FILE1, "$ file1") or die "Input file can not be opened: $!"; Open (FILE2, "<$ file2") or dead "Input file can not be opened: $!"; While (& lt; FILE1 & gt;) {chomp; $ Count1 ++; # Skip headers; Until next $ count1; My $ row_1; @ $ Row_1 = partition (/, /, $ _); Push @ $ letter1, $ row_1; } @ $ Sheet_1 = Sort {$ a- & gt; [0] & lt; = & Gt; $ B- & gt; [0]} @ $ sheet; While (& lt; FILE2 & gt;) {chomp; $ COUNT2 ++; # Skip headers; Until next $ count2; My $ row_2; @ $ Row_2 = Partition (/, /, $ _); Push @ $ letter_2, $ line_2; } @ $ Sheet_2 = Sort {$ a- & gt; [0] & lt; = & Gt; $ B- & gt; [0]} @ $ letter_2; OUTER: {foreach my $ row_1 (@ $ sheet_1) {foreach my $ row_2 (@ $ sheet_2) {if (@ $ row_1 [0] eq @ $ row_2 [0]) {last OUTER} other {print "@ $ row_1 [0] \ n "; }}}} Closed FILE1; Close FILE2;    

You can use the Pearl module to do this. Otherwise, see below:

Here's an algorithm to compare.

  Use strict; My @ arr1; My @ arr2; My $ a; Open (FIL, "a.txt") or die ("$!"); While (& lt; FIL & gt;) {chomp; $ One = $ _; $ A = ~ s / [\ t;,] * // g; Push @ arr1, $ a if ($ a ne '');}; Close (fil); Open (FIL, "B.text") or die ("$!"); While (& lt; FIL & gt;) {chomp; $ One = $ _; $ A = ~ s / [\ t;,] * // g; Push @ arr2, $ a if ($ a ne '');}; Close (fil); My% arr1hash; My% arr2hash; My @dirfer; Forex Currency (@ AR1) {$ arr1hash {$ _} = 1; } Foreach (@ arr2) {$ arr2hash {$ _} = 1; } Foreach $ a (@ arr1) {If (not defined ($ arr2hash {$ a})) {push @diffarr, $ a; }} Foreach $ a (@ arr2) {If (not defined ($ arr1hash {$ a})) {push @diffarr, $ a; }} Print "Def: \ n"; Foreign currency $ a (@df) {print "$ a \ n"; } # You can print a file instead of: print FIL "$ a \ n";    

No comments:

Post a Comment