How can I use Perl to determine whether the contents of two files are identical?
- by Zaid
This question comes from a need to ensure that changes I've made to code doesn't affect the values it outputs to text file. Ideally, I'd roll a sub to take in two filenames and return 1or return 0 depending on whether the contents are identical or not, whitespaces and all.
Given that text-processing is Perl's forté, it should be quite easy to compare two files and determine whether they are identical or not (code below untested).
use strict;
use warnings;
sub files_match {
my ( $fileA, $fileB ) = @_;
open my $file1, '<', $fileA;
open my $file2, '<', $fileB;
while (my $lineA = <$file1>) {
next if $lineA eq <$file2>;
return 0 and last;
}
return 1;
}
The only way I can think of (sans CPAN modules) is to open the two files in question, and read them in line-by-line until a difference is found. If no difference is found, the files must be identical.
But this approach is limited and clumsy. What if the total lines differ in the two files? Should I open and close to determine line count, then re-open to scan the texts? Yuck.
I don't see anything in perlfaq5 relating to this. I want to stay away from modules unless they come with the core Perl 5.6.1 distribution.