If you have enough memory, you could just have a hash that goes from the normalized contents of the files to the name of the file. That moves the logic to a hash lookup. But if you have tons of files, well you probably don't have that much memory.

But you can still use the same strategy using md5 hashes. And indeed here is some (partially tested) sample code for this problem:

#! /usr/bin/perl -w use strict; use Digest::MD5 qw(md5); my %file_hash; foreach my $file (@ARGV) { my $key = md5(normalize_text(slurp_file($file))); push @{$file_hash{$key}}, $file; } foreach my $files (values %file_hash) { if (@$files < 2) { next; } else { # $files is an anonymous array of files, which # are *probably* all duplicates of each other. # Put appropriate logic here. Were it not for # memory limits, *this* would be the whole # script! my %file_of; foreach my $file (@$files) { my $text = normalize_text(slurp_file($file)); if (exists $file_of{ $text }) { print "$file_of{$text} and $file are dups\n"; unlink($file) or die "Cannot delete $file: $!"; } else { $file_of{$text} = $file; } } } } # Takes text, normalizes whitespace and returns it. sub normalize_text { my $text = shift; $text =~ s/\s+/ /g; $text =~ s/^ //; $text =~ s/ \z//; $text; } # Takes a file, returns the contents in a string sub slurp_file { local @ARGV = shift; local $/; <>; }

In reply to Re (tilly) 1: Comparing two files by tilly
in thread Comparing two files by ram

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.