How can I use Perl to determine whether the contents of two files are identical?

后端 未结 2 1708
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 18:10

This question comes from a need to ensure that changes I\'ve made to code doesn\'t affect the values it outputs to text file. Ideally, I\'d roll a sub to take in two filenam

相关标签:
2条回答
  • 2020-12-09 18:47

    There are a couple of O(1) checks you can do first to see if the files are different.

    If the files have different sizes, then they are obviously different. The stat function will return the sizes of the files. It will also return another piece of data that will be useful: the inode number. If the two files are really the same file (because the same filename was passed in for both files or because both names are hardlinks for the same file), the inode number will be the same. A file is obviously the same as itself. Baring those two checks there is no better way to compare two local files for equivalence other than to directly compare them against each other. Of course, there is no need to do it line by line, you can read in larger blocks if you so desire.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use File::Compare ();
    
    sub compare {
        my ($first, $second)             = @_;
        my ($first_inode, $first_size)   = (stat $first)[1, 7];
        my ($second_inode, $second_size) = (stat $second)[1, 7];
    
        #same file, so must be the same;
        return 0 if $first_inode == $second_inode;
    
        #different sizes, so must be different
        return 1 unless $first_size == $second_size;
    
        return File::Compare::compare @_;
    }
    
    print compare(@ARGV) ? "not the " : "", "same\n";
    
    0 讨论(0)
  • 2020-12-09 19:02

    It's in the core.

    use File::Compare;
    
    if (compare("file1", "file2") == 0) {
      print "They're equal\n";
    }
    
    0 讨论(0)
提交回复
热议问题