Compare Files in Perl

Posted on 2011-10-21
Last Modified: 2012-08-13

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.


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

Question by:new_perl_user
    LVL 28

    Expert Comment

    LVL 26

    Accepted Solution

    This should do what you want...
    # 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

    LVL 26

    Expert Comment

    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.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Suggested Solutions

    On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
    Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now