Comparing two directories using Perl

后端 未结 3 1272
太阳男子
太阳男子 2021-01-16 05:40

i am new to Perl so excuse my noobness,

Here\'s what i intend to do.

$ perl dirComp.pl dir1 dir2

dir1 & dir2 are directory nam

3条回答
  •  死守一世寂寞
    2021-01-16 05:50

    The example you supplied using File::DirCompare works as intended.

    Keep in mind that the callback subroutine is called for every unique file in each directory and for every pair of files which differ in their content. Having the same filename is not enough, the contents of each file in each directory must be exactly the same as well.

    Furthermore, the cases in which you report "PASSED" aren't a success at all (by your definition) since they detail the cases in which a file exists in one of the directories, but not the other: meaning the directories' contents are not identical.

    This should be closer to what you want:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use File::DirCompare;
    use File::Basename;
    
    sub compare_dirs
    {
      my ($dir1, $dir2) = @_;
      my $equal = 1;
    
      File::DirCompare->compare($dir1, $dir2, sub {
        my ($a,$b) = @_;
        $equal = 0; # if the callback was called even once, the dirs are not equal
    
        if ( !$b )
        {
          printf "File '%s' only exists in dir '%s'.\n", basename($a), dirname($a);
        }
        elsif ( !$a ) {
          printf "File '%s' only exists in dir '%s'.\n", basename($b), dirname($b);
        }
        else
        {
          printf "File contents for $a and $b are different.\n";
        }
      });
    
      return $equal;
    }
    
    print "Please specify two directory names\n" and exit if (@ARGV < 2);
    printf "%s\n", &compare_dirs($ARGV[0], $ARGV[1]) ? 'Test: PASSED' : 'Test: FAILED';
    

提交回复
热议问题