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

new_perl_userAsked:
Who is Participating?
 
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
 
FishMongerCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.