Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do compare two files using Perl?

Little tricks

How do compare two files using Perl?

by  MikeLacey  Posted    (Edited  )
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.
[tt]
# read all of file1
open(F,"file1")||die;
while(<F>){
$file1hash{$_}=1; # into a hash array
}
close(F);

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


Mike
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top