How to compare two files if they are the same in Perl

Overview

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.

Syntax

compare(file1, file2)

Parameters

  • file1: The first of the two files we want to compare.
  • file2: The second of the two files we want to compare.

Return value

1 is returned if the files are not the same. 0 is returned if the files are the same.

Example

Let’s look at the code below:

main.perl
test2.txt
test1.txt
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 results
print $r1;
print "\n$r2";
print "\n$r3";

Explanation

We create the files test1 and test2 along with our application code file main.perl.

  • Lines 4 to 6: We get the files.
  • Lines 9 to 11: We compare the files and got the results.
  • Lines 14 to 16: We print the results to the console.

Free Resources