You can use the following Perl script to compare two files. But please note that such practice should not be encouraged. When you already have the commands to do the job, writing your own script to do the same is not recommended.
#!/usr/bin/perl
# file_compare.pl
# Purpose: compare two files and show differences
# usage: file_compare.pl filename1 filename2
use strict;
use warnings;
my $file1 = shift or die "filename missing \n";
my $file2 = shift or die "filename missing \n";
open (FILE1, "< $file1") or die "Can not read file $file1: $! \n";
my @file1_contents = <FILE1>; # read entire contents of file
close (FILE1);
open (FILE2, "< $file2") or die "Can not read file $file2: $! \n";
my @file2_contents = <FILE2>; # read entire contents of file
close (FILE2);
my $length1 = $#file1_contents; # number of lines in first file
my $length2 = $#file2_contents; # number of lines in second file
if ($length1 > $length2) {
# first file contains more lines than second file
my $counter2 = 0;
foreach my $line_file1 (@file1_contents) {
chomp ($line_file1);
if \(defined \($file2_contents[$counter2]\)\) \{
\# line exists in second file
chomp \(my $line_file2 = $file2_contents[$counter2]\);
if \($line_file1 ne $line_file2\) \{
print "\\nline " . \($counter2 \+ 1\) . " \\n";
print "< $line_file1 \\n" if \($line_file1 ne ""\);
print "--- \\n";
print "> $line_file2 \\n\\n" if \($line_file2 ne ""\);
\}
\}
else \{
\# there is no line in second file
print "\\nline " . \($counter2 \+ 1\) . " \\n";
print "< $line_file1 \\n" if \($line_file1 ne ""\);
print "--- \\n";
print "> \\n"; \# this line does not exist in file2
\}
$counter2\+\+; \# point to the next line in file2
\}
}
else {
# second file contains more lines than first file
# or both have equal number of lines
my $counter1 = 0;
foreach my $line_file2 (@file2_contents) {
chomp ($line_file2);
if \(defined \($file1_contents[$counter1]\)\) \{
\# line exists in first file
chomp \(my $line_file1 = $file1_contents[$counter1]\);
if \($line_file1 ne $line_file2\) \{
print "\\nline " . \($counter1 \+ 1\) . " \\n";
print "< $line_file1 \\n" if \($line_file1 ne ""\);
print "--- \\n";
print "> $line_file2 \\n" if \($line_file2 ne ""\);
\}
\}
else \{
\# there is no line in first file
print "\\nline " . \($counter1 \+ 1\) . " \\n";
print "< \\n"; \# this line does not exist in file1
print "--- \\n";
print "> $line_file2 \\n" if \($line_file2 ne ""\);
\}
$counter1\+\+; \# point to next line in file1
\}
Merged your two threads as you are still asking the same question - and I'll repeat the question asked already - Why don't you want to use diff, cmp, or comm?