Objective was to find whether a line in one file exists in the other or not. This small prog compares 2 text files line per line, ignoring blank lines and lines begining with #. I sort the 2 files to make sure i traverse just once thru them. it is actually used in my company to check files against templates, hope u find it useful ...
######################################################################
+##
#Usage: perlscript [-w] -t template -d dump [-o outputfile]
#where -w enables warnings i.e. warns of extra lines in the dump whic
+h are not there in the template
# -t template is the file u compare against
# -d dump is what u check (its dump 'cos i was checking the dump
+ of another prog against a template)
#if output file is not give ouput does to STDOUT
#
#Author: thesundayman(saurabhchandra@hotmail.com)
######################################################################
+####
$DEBUG = 0;
handleArgs();
if($outfile) {
open (STDOUT, ">$outfile") || die "Cannot redirect STDOUT\n";
}
open(TEMP,$dump) || die "Error opening $dump\n";
open(FILE,$template) || die "Error opening $template\n";
while(<TEMP>)
{
tr/A-Z/a-z/;
push(@temp, $_);
}
while(<FILE>)
{
tr/A-Z/a-z/;
push(@file, $_);
}
@temp = sort(@temp);
@file = sort(@file);
OUTER:
foreach $_ (@file)
{
next if /^\s*$/; #ignore empty lines
next if /^\s*#/; #ignore comments
chomp;
$_ = lc;
while(@temp)
{
$x = shift @temp;
next if ($x =~ /^\s*$/);
next if ($x =~ /^\s*#/);
chomp $x;
$comparison = $_ cmp $x;
print "$_ - $x = $comparison\n" if $DEBUG;
if($comparison > 0)
{
print "Warning $x not expected....\n" if $W;
next;
}
elsif ($comparison < 0)
{
print "Not Found $_\n";
unshift(@temp, $x);
next OUTER;
}
elsif ($comparison == 0) {
print "Found $_ \n";
next OUTER;
}
}
print "Not found $_\n";
}
if($W)
{
foreach $temp (@temp) { print "Warning $temp not expected\n";}
}
sub handleArgs()
{
while(@ARGV)
{
print "In Handle args\n" if $DEBUG;
#Enable warnings
if($ARGV[0] =~ /-W/i)
{
$W = 1; shift(@ARGV);
}
elsif($ARGV[0] =~ /-t/i)
{
$template = $ARGV[1]; splice(@ARGV, 0, 2);
}
elsif($ARGV[0] =~ /-d/i)
{
$dump = $ARGV[1]; splice(@ARGV, 0, 2);
}
elsif($ARGV[0] =~ /-O/i)
{
$outfile = $ARGV[1]; splice(@ARGV, 0, 2);
}
else
{
print "Invalid Arg in FileCmp ", shift (@ARGV),"\n";
}
}
}