cool_ravi2 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am looking for a perl program or module that would compare two binary files, executables and inform if they are same or not? Regards, Ravi.

Replies are listed 'Best First'.
Re: Binary diff in Perl
by atcroft (Abbot) on Sep 29, 2004 at 16:46 UTC

    Probably the quickest way I can think of would be to use one of the Digest::* modules, such as Digest::MD5 to compute a digest of the two files, and compare those. Taking from the sample code of the Digest::MD5 module, the following (*untested*) code might do something along the lines of what you wish. (Filenames would be provided on the command line.)

    #!/usr/bin/perl -w use strict; use Digest::MD5; if (! scalar(@ARGV)) { print <<USAGE; Usage: $0 file1 file2 ... fileN USAGE exit; } my (%md5sums); foreach my $filename (@ARGV) { open(FILE, $filename) or die("Can't open '$filename': $!"); binmode(FILE); my $digest = Digest::MD5->new->addfile(*FILE)->hexdigest; $md5sums{'by-name'}{$filename} = $digest; push(@{$md5sums{'by-digest'}{$digest}}, $filename); close(FILE); } print "By checksum:\n"; foreach my $digest (sort(keys(%{$md5sums{'by-digest'}}))) { print $digest, ": \n"; foreach my $filename (sort(@{$md5sums{'by-digest'}{$digest}})) { print "\t", $filename, "\n"; } } print "\n"; print "By filename:\n"; foreach my $filename (sort(keys(%{$md5sums{'by-name'}}))) { print $md5sums{'by-name'}{$filename}, ': ', $filename, "\n"; }
Re: Binary diff in Perl
by saintmike (Vicar) on Sep 29, 2004 at 16:28 UTC
    Use Digest::MD5's addfile() method to determine the digests of each file and then compare the two. Alternatively, calculate a fast but less reliable System V checksum, like described in unpack:
    $checksum = do { local $/; # slurp! unpack("%32C*",<>) % 65535; };
Re: Binary diff in Perl
by diotalevi (Canon) on Sep 29, 2004 at 16:29 UTC

    File::Compare

    or

    compare( 'invoices.txt', 'invoices.bak' ); sub compare { local *FH_A; local *FH_B; open FH_A, "< $_[0]\0" or die "Can't open $_[0] for reading: $!"; open FH_B, "< $_[1]\0" or die "Can't open $_[1] for reading: $!"; binmode FH_A or die "Can't binmode $_[0]: $!"; binmode FH_B or die "Can't binmode $_[1]: $!"; local $/ = \ 4096; 1 while <FH_A> eq <FH_B>; return eof *FH_A and eof *FH_B; }
Re: Binary diff in Perl
by TedPride (Priest) on Sep 30, 2004 at 00:11 UTC
    diotalevi seems to have the right answer if all you want to do is compare files once. If on the other hand you want to determine which files have changed since the last check, you're better off either comparing timestamps, or if that isn't enough, storing MD5 hashes and using those to compare.