简体   繁体   中英

How can I compare two files and show differences in Perl?

I'm trying to write Perl script to compare the content of 2 files so that it would list out any differences seen. Trying the following but I'm not sure how to continue further. Note that following is only part of the script as I have sorted the content of the 2 files beforehand. Thanks in advance.

open (FILE1, "log") || die ("Can't open file log for reading") ;
open (FILE2, "master") || die ("Can't open file master for reading") ;

@file1 = <FILE1> ;
@file2 = <FILE2> ;

#$perlcompare = (compare('log','master')== 0) ;
#die ("Log and master files are equal and match.\n") ;

if (@file1 eq @file2) {

print "Log and master are equal and match.\n" ;
} else  ????????????

exit 0;

If you need to stay within Perl, there is File::Compare which will just compare the files.

For showing differences, there is Text::Diff .

C:\Temp> cat file1
1
2
3
4
5
C:\Temp> cat file2
1
2
3
5
#!/usr/bin/env perl

use strict; use warnings;

use Text::Diff;

my $diffs = diff 'file1' => 'file2';

print $diffs;

Output

C:\Temp> t
--- file1       Fri Nov 18 00:01:40 2011
+++ file2       Fri Nov 18 00:01:49 2011
@@ -1,5 +1,4 @@
 1
 2
 3
-4
+5
-5

如果您可以使用perl以外的其他任何东西,我建议diff(1)或comm(1)

comm -3 sorted-file-1 sorted-file-2
#!/usr/bin/perl
use strict;
use warnings;
use List::Compare;

open (my $log, "<", "log") or die $!;
open (my $master, "<", "master") or die $!;
my @content_log=<$log>;
my @content_master=<$master>;

my $lc = List::Compare->new(\@content_log, \@content_master);    
my @intersection = $lc->get_intersection;
my @firstonly = $lc->get_unique;
my @secondonly = $lc->get_complement;

print "Common Items:\n"."@intersection"."\n";
print "Items Only in First List:\n"."@firstonly"."\n";
print "Items Only in Second List:\n"."@secondonly"."\n";

print "log\n", $lc->get_unique,"\n"; 
print "master\n", $lc->get_complement,"\n"; 

close $log;
close $master;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM