We can compare two files to see if they are the same in Perl using the compare()
method. It is a method of the subroutine File::Compare
. It compares files line by line. If a difference is detected, it stops. If the files are the same, it returns 0
. Otherwise it returns 1
.
compare(file1, file2)
file1
: The first of the two files we want to compare.file2
: The second of the two files we want to compare.1 is returned if the files are not the same. 0 is returned if the files are the same.
Let’s look at the code below:
use File::Compare;# get files$file1 = "main.perl";$file2 = "test1.txt";$file3 = "test2.txt";# compare files$r1 = compare($file1, $file2);$r2 = compare($file2, $file3);$r3 = compare($file3, $file1);# print resultsprint $r1;print "\n$r2";print "\n$r3";
We create the files test1
and test2
along with our application code file main.perl
.