Advertisement
rplantiko

Keywise diff of two .csv data files

Dec 11th, 2020 (edited)
1,449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.99 KB | None | 0 0
  1. # Compare the values of the second column of two .csv files
  2. # Using the first column as key
  3. # Ignoring keys which only exist in second file
  4. # Result .csv contains new and old values for each key,
  5. # and additionally the percentual in- or decrease in a fourth column
  6.  
  7. use constant {
  8.   BASE_DIR => "G:\\MY_BASE_DIRECTORY\\",
  9.   SEP      => "\t"   # Separator used in .csv files
  10. };
  11.  
  12. use Text::CSV qw( csv );
  13.  
  14. my $fnew = read_csv( "kw-49-2020.csv" );
  15. my $fold = read_csv( "kw-47-2020.csv" );
  16.  
  17. while (my ($key, $new) = each %$fnew) {
  18.  
  19.   print "$key".SEP."$new";
  20.  
  21.   if (my $old = $fold->{$key}) {
  22.     print SEP."$old";
  23.     my $trend = 100 * ( $new - $old ) / $old;
  24.     printf( SEP."%.2f",$trend );
  25.   }
  26.   print "\n";
  27. }
  28.  
  29. sub read_csv {
  30.  
  31.   my $aoa = csv (in => BASE_DIR . shift, sep_char=> SEP );
  32.   my %stats = ();
  33.   for my $line (@$aoa) {
  34.     my @record = @$line;
  35.     my $key = ( $record[0] =~ s/^\s*(\w+)\s*/$1/r );
  36.     $stats{$key} = $record[1];
  37.   }
  38.  
  39.   return \%stats;  
  40.    
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement