KIASohc has asked for the wisdom of the Perl Monks concerning the following question:
Good day to All!
Hope all is well with everyone. I just would like to ask for some help with a few items with my code.
I am trying compare 2 CSV files and print/display their differences. So far, it is working up to that point.
My problem now are the following:
I would like to group the records in such a way that
- It groups the unmatched records together
- Display the row number corresponding to these records row position from the file
- A comma is used as a separator
Unfortunately, I am unable to do them. Below is a sample data and a sample of what is currently happening and how I want it to appear.
Here is a sample of my data:
FILE 1 Content:
NAME,SURNAME,AGE,GENDER
PAUL,SMITH,28,MALE
RICK,SULLIVAN,31,MALE
SILVIA,CONOR,24,FEMALE
VANI,LOVE,26,FEMALE
FILE 2 Content:
NAME,SURNAME,AGE,GENDER
PAUL,SMITH,28,MALE
RICK,SULLIVAN,30,MALE < -- this row contains a mismatch
SILVIA,CONOR,24,MALE < -- this row contains a mismatch
VANI,LOVE,26,FEMALE
These 2 files are expected to have the same contents
CURRENT OUTPUT:
-------------------------------------------------------------
Row 1 – RICKSULLIVAN31MALE
Row 2 – SILVIACONOR24FEMALE
Row 3 – RICKSULLIVAN30MALE
Row 4 – SILVIACONOR24MALE
-------------------------------------------------------------
Note: I am aware that using print $count++ causes the row number just to increment. I just want to see how it would look like on my output.
EXPECTED OUTPUT:
-------------------------------------------------------------
Row 3 – RICK,SULLIVAN,31,MALE
Row 3 – RICK,SULLIVAN,30,MALE
Row 4 – SILVIA,CONOR,24,FEMALE
Row 4 – SILVIA,CONOR,24,MALE
-------------------------------------------------------------
Thanks in advance!
Here is the code:
#! /usr/bin/perl use strict; use warnings; my @arr1; my @arr2; my $a; #COMPARE 2 FILES open(FIL,'FILE1.CSV') or die "$!"; #open(FIL,$file) or die "$!"; while (<FIL>) { $a=$_; $a =~ s/[\t;, ]*//g; push @arr1, $a if ($a ne ''); }; close(FIL); open(FIL,'FILE2.csv') or die "$!"; while (<FIL>) { $a=$_; $a =~ s/[\t;, ]*//g; push @arr2, $a if ($a ne ''); }; close(FIL); my %arr1hash; my %arr2hash; my @diffarr; foreach(@arr1) {$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; } } my $dir = '/perl/test/run'; opendir(DIR, $dir) or die $!; while (my $file = readdir(DIR)) { next unless (-f "$dir/$file"); next unless ($file =~ m/\.csv$/); print "\n"; printf "Source: $file "; print "\n"; my $count=1; foreach $a(@diffarr) { print "Item "; print $count++ ; print " - "; print ($a); } } print "\n";
|
|---|