• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

Compare Files in Perl

Hi,

I want to compare two txt files File A and File B and print the missing values that are  in File A but not File B

I tried one of the script as below  but no output. Can some one pls help.


#!/usr/local/bin/perl


open F1, "< /usr/HOME/DATA/sample.txt";
open F2, "< /usr/HOME/LOGS/out.txt";

my %hash1;
my %hash2;

while (<F1>) { $hash1{$_} = 1; }
while (<F2>) { $hash2{$_} = 1; }

print "Data in File A but not in File B are:\n";
foreach (keys %hash1) { print if !defined($hash2{$_}); }


close F1;

Open in new window

0
new_perl_user
Asked:
new_perl_user
  • 2
1 Solution
 
FishMongerCommented:
0
 
wilcoxonCommented:
This should do what you want...
#!/usr/local/bin/perl

# always use strict and warnings
use strict;
use warnings;

open IN, '</usr/HOME/DATA/sample.txt' or die "could not open sample.txt: $!";
my %hash1 = map { chomp; $_ => 1 } <IN>;
close IN;
open IN, '</usr/HOME/LOGS/out.txt' or die "could not open out.txt: $!";
my %hash2 = map { chomp; $_ => 1 } <IN>;
close IN;

print "Data in File A but not in File B:\n";
foreach my $key (keys %hash1) {
    print $key, "\n" unless exists($hash2{$key});
}

Open in new window

0
 
wilcoxonCommented:
File::Compare will tell you if the files are the same or not but will not list the values that exist in File A but not in File B.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now