4 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $Too_Big *FROM *TO);
11 @EXPORT = qw(compare);
12 @EXPORT_OK = qw(cmp compare_text);
14 $Too_Big = 1024 * 1024 * 2;
17 # Version of File::Compare
18 return $File::Compare::VERSION;
22 croak("Usage: compare( file1, file2 [, buffersize]) ")
23 unless(@_ == 2 || @_ == 3);
25 my ($from,$to,$size) = @_;
26 my $text_mode = defined($size) && $size < 0;
28 my ($fromsize,$closefrom,$closeto);
31 croak("from undefined") unless (defined $from);
32 croak("to undefined") unless (defined $to);
35 (UNIVERSAL::isa($from,'GLOB') || UNIVERSAL::isa($from,'IO::Handle'))) {
37 } elsif (ref(\$from) eq 'GLOB') {
40 open(FROM,"<$from") or goto fail_open1;
49 (UNIVERSAL::isa($to,'GLOB') || UNIVERSAL::isa($to,'IO::Handle'))) {
51 } elsif (ref(\$to) eq 'GLOB') {
54 open(TO,"<$to") or goto fail_open2;
55 binmode TO unless $text_mode;
59 if (!$text_mode && $closefrom && $closeto) {
60 # If both are opened files we know they differ if their size differ
61 goto fail_inner if $fromsize != -s TO;
67 while (defined($fline = <FROM>)) {
68 unless (defined($tline = <TO>) && $fline eq $tline) {
72 goto fail_inner if defined($tline = <TO>);
75 unless (defined($size) && $size > 0) {
77 $size = 1024 if $size < 512;
78 $size = $Too_Big if $size > $Too_Big;
81 my ($fr,$tr,$fbuf,$tbuf);
83 while(defined($fr = read(FROM,$fbuf,$size)) && $fr > 0) {
84 unless (defined($tr = read(TO,$tbuf,$fr)) && $tbuf eq $fbuf) {
88 goto fail_inner if defined($tr = read(TO,$tbuf,$size)) && $tr > 0;
91 close(TO) || goto fail_open2 if $closeto;
92 close(FROM) || goto fail_open1 if $closefrom;
96 # All of these contortions try to preserve error messages...
98 close(TO) || goto fail_open2 if $closeto;
99 close(FROM) || goto fail_open1 if $closefrom;
108 $! = $status unless $!;
116 # Using a negative buffer size puts compare into text_mode
117 sub compare_text { compare(@_[0..1], -1) }
125 File::Compare - Compare files or filehandles
131 if (compare("file1","file2") == 0) {
132 print "They're equal\n";
137 The File::Compare::compare function compares the contents of two
138 sources, each of which can be a file or a file handle. It is exported
139 from File::Compare by default.
141 File::Compare::cmp is a synonym for File::Compare::compare. It is
142 exported from File::Compare only by request.
144 File::Compare::compare_text does a line by line comparison of the two
145 files. It stops as soon as a difference is detected.
149 File::Compare::compare return 0 if the files are equal, 1 if the
150 files are unequal, or -1 if an error was encountered.
154 File::Compare was written by Nick Ing-Simmons.
155 Its original documentation was written by Chip Salzenberg.