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

I have a question that hopefully someone will be able to help me with. I have been asked to write a script which will take the contents of a text file (f1) and compare it to the contents of a second file (f2). I then need to be able to write any differences between the two files to a third file (f3). The output needs to include anything that has been added, deleted, or modified from f1. Unfortunately, it would be easier if I could do this without having to install any modules. The process of getting software approved for installation at work is long and tedious. Is this possible or should I just try doing it in Python or some other language? Thanks in advance

Replies are listed 'Best First'.
Re: Help with document comparison
by GrandFather (Saint) on Jan 12, 2010 at 20:37 UTC

    Diffing files is a complicated process. You really don't want to have to reinvent that wheel. Using Algorithm::Diff as suggested above is the way to do it. Unless some other language has an equivalent to Algorithm::Diff there is no advantage at all to using that language. However, you may find Yes, even you can use CPAN helpful.


    True laziness is hard work
Re: Help with document comparison
by kennethk (Abbot) on Jan 12, 2010 at 19:59 UTC
Re: Help with document comparison
by happy.barney (Friar) on Jan 12, 2010 at 19:30 UTC
    what about shell? diff is your friend.
Re: Help with document comparison
by dHarry (Abbot) on Jan 13, 2010 at 12:42 UTC

    Last year I copied some code by Dominus from Perlmonks, can't find the original node though. I've copy/pasted the script for you. It might help you get started.

    #!/usr/bin/perl # # `Diff' program in Perl # Copyright 1998 M-J. Dominus. (mjd-perl-diff@plover.com) # # This program is free software; you can redistribute it and/or modify + it # under the same terms as Perl itself. # use Algorithm::Diff qw(diff); bag("Usage: $0 oldfile newfile") unless @ARGV == 2; my ($file1, $file2) = @ARGV; # -f $file1 or bag("$file1: not a regular file"); # -f $file2 or bag("$file2: not a regular file"); -T $file1 or bag("$file1: binary"); -T $file2 or bag("$file2: binary"); open (F1, $file1) or bag("Couldn't open $file1: $!"); open (F2, $file2) or bag("Couldn't open $file2: $!"); chomp(@f1 = <F1>); close F1; chomp(@f2 = <F2>); close F2; $diffs = diff(\@f1, \@f2); exit 0 unless @$diffs; foreach $chunk (@$diffs) { foreach $line (@$chunk) { my ($sign, $lineno, $text) = @$line; printf "%4d$sign %s\n", $lineno+1, $text; } print "--------\n"; } exit 1; sub bag { my $msg = shift; $msg .= "\n"; warn $msg; exit 2; }
Re: Help with document comparison
by rspishock (Monk) on Jan 14, 2010 at 13:59 UTC
    Thanks for all of your help. Sadly I think I will have to use shell for this script since getting the approval to install the algorithm::diff module could take three weeks or longer to come through.