Compare two text files (Perl)

This code can be found in Chapter 8 of Windows XP Cookbook

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the Perl code from this site.

# From the book "Windows XP Cookbook"
# ISBN: 0596007256

# ------ SCRIPT CONFIGURATION ------

use Win32::OLE;
use constant vbNewLine => "\r\n";

$strFile1 = '<FilePath1>';
# e.g. c:\scripts\test1.vbs
$strFile2 = '<FilePath2>';
# e.g. c:\scripts\test2.vbs
# ------ END CONFIGURATION ---------
$objFSO = Win32::OLE->new('Scripting.FilesystemObject');
$objFile1 = $objFSO->OpenTextFile($strFile1, 1);
$objFile2 = $objFSO->OpenTextFile($strFile2, 1);
$arrFile1 = VBS::Split($objFile1->ReadAll, vbNewLine);
$arrFile2 = VBS::Split($objFile2->ReadAll, vbNewLine);
$objFile1->Close();
$objFile2->Close();

if ($#$arrFile1 < $#$arrFile2) {
    $intLineCount = $#$arrFile1;
    $strError = $strFile2 . ' is bigger than ' . $strFile1;
}
elsif ($#$arrFile1 > $#$arrFile2) {
    $intLineCount = $#$arrFile2;
    $strError = $strFile2 . ' is bigger than ' . $strFile1;
}
else {
    $intLineCount = $#$arrFile2;
}

for my $i (0 .. $intLineCount) {
    last if !(_compareValues(arrFile1($i), arrFile2($i), 2));
}

if ($i < ($intLineCount + 1)) {
    print 'Line ' . ($i + 1) . ' not equal', "\n";
    print "$strError\n";
}
elsif ($strError ne '') {
    print "$strError\n";
}
else {
    print "Files are identical.\n";
}

sub _isNumeric {
    no warnings qw(numeric);
    return ($_[0] + 0) eq $_[0];
}

sub _compareValues {
    my($lhs, $rhs, $cval) = @_;
    my $cmpVal= (_isNumeric($lhs) || _isNumeric($rhs)) ? ($lhs <=> $rhs) : ($lhs cmp $rhs);
    # Map (-1, 0, 1) => (1, 2, 4) and do a bit-and
    return $cval & (1, 2, 4)[$cmpVal + 1];
}


package VBS;
use strict;
sub Split {
    my($expression, $delim, $count, $compare) = @_;
    my $re;
    $delim =~ s/\r//g;
    if (!defined $delim || !length($delim)) {
	$re = qr/\s/;
    }
    else {
	$re = $compare ? qr/\Q$delim\E/i : qr/\Q$delim\E/;
    }
    if (!defined $count || $count == -1) {
        return [CORE::split($re, $expression)];
    }
    else {
        return [CORE::split($re, $expression, $count)];
    }
}

This code has been viewed 3992 times.

New from the creators of TechTasks.com: StatSheet.com