×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

Little tricks

How do compare two files using Perl? by MikeLacey
Posted: 22 Dec 01 (Edited 22 Jun 04)

Please browse through FAQ219-2884 and FAQ219-2889 first. Comments on this FAQ and the General FAQ's are very welcome.

Now two ways to do it, the easy way:

        use File::Compare;
        if (compare("file1","file2") == 0) {
            print "They're equal\n";
        }

Just found this, surprised no one picked me up on it earlier....

And the, slightly, harder way that gives you more info but only works with text files.

A way to read each line of FILE1 then read the complete FILE2 and print each line from FILE2 that is not found in FILE1.

If file1 is small enough to read into memory you could do something like this.
[b]
# read all of file1
open(F,"file1")||die;
while(<F>){
  $file1hash{$_}=1; # into a hash array
}
close(F);

# create the output file
open(OF,&quot;out.file&quot;)||die;
# then read through file2
open(F,&quot;file2&quot;)||die;
while(<F>){
  print OF $_ unless defined($file1hash{$_});
}
close(F);
[/b]

Mike

Back to Perl FAQ Index
Back to Perl Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close