Ramse
Ramse

Reputation: 144

Compare multiple file contents in perl

I have list of files (more than 2) where I need to verify whether all of those files are identical.

I try to use File::Compare module , But it seems to accept only two files. But in my case I have multiple files where I want to verify its contents are same? Do we have any other way for my requirement.

Upvotes: 1

Views: 97

Answers (1)

Sobrique
Sobrique

Reputation: 53508

The solution to this problem is to take a digest of every file. Many options exist, most will be 'good enough' (e.g. technically MD5 has some issues, but they're not likely to matter outside a cryptographic/malicious code scenario).

So simply:

#!/usr/bin/perl

use strict;
use warnings;

use Digest::MD5 qw ( md5_hex );
use Data::Dumper;

my %digest_of;
my %unique_files;

foreach my $file (@ARGV) {
    open( my $input, '<', $file ) or warn $!;
    my $digest =  md5_hex ( do { local $/; <$input> } );
    close ( $input ); 
    
    $digest_of{$file} = $digest;
    push @{$unique_files{$digest}}, $file; 
}

print Dumper \%digest_of;
print Dumper \%unique_files;

%unique_files will give you each unique fingerprint, and all the files with that fingerprint - if you've got 2 (or more) then you've got files that aren't identical.

Upvotes: 6

Related Questions