确定输入是文件还是目录



我目前正在编写一个程序,该程序最终将比较两个目录中的文件并显示每个文件中已更改的功能。但是,在检查目录中的内容是文件还是子目录时,我遇到了问题。

现在,当我检查它是否只是一个带有-d检查的目录时,它没有捕获任何子目录。我在下面发布了我的部分代码。

opendir newDir, $newDir;
my @allNewFiles = grep { $_ ne '.' and $_ ne '..'} readdir newDir;
closedir newDir;
opendir oldDir, $oldDir;
my @allOldFiles = grep { $_ ne '.' and $_ ne '..'} readdir oldDir;
closedir oldDir;

foreach (@allNewFiles) {
    if(-d $_) {
        print "$_ is not a file and therefore is not able to be comparednn";
    } elsif((File::Compare::compare("$newDir/$_", "$oldDir/$_") == 1)) {
        print "$_ in new directory $newDirName differs from old directory $oldDirNamenn";
        print OUTPUTFILE "File: $_ has been update. Please check marked functions for differencesn";
        print OUTPUTFILE "nn";
        print OUTPUTFILE "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=nn";
    } elsif((File::Compare::compare("$newDir/$_", "$oldDir/$_") < 0)) {
        print "$_ found in new directory $newDirName but not in old directory $oldDirNamen";
        print "Entire file not printed to output file but instead only file namen";
        print OUTPUTFILE "File: $_ is a new file!nn";
        print OUTPUTFILE "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=nn";
    }
 }
foreach (@allOldFiles) {
    if((File::Compare::compare("$newDir/$_", "$oldDir/$_") < 0)) {
        print "$_ found in old directory $oldDirName but not in new directory $newDirNamenn";
    }
 }

正如perldoc -f readdir所说:

如果您打算从 readdir 中对返回值进行文件测试, 您最好在有问题的目录前面加上前缀。否则,因为我们 没有 chdir 在那里,它会测试错误的文件。

if(-d "$newDir/$_") {

使用 Path::Class

use strict;
use warnings;
use Path::Class;

my @allNewFiles = grep { !$_->is_dir } dir("/newDir")->children;

使用递归调用首先获取文件列表,然后对它们进行操作。

my $filesA = {};
my $filesB = {};
# you are passing in a ref to filesA or B so no return is needed.
sub getFiles {
  my ($dir, $fileList) = @_;
  foreach my $file (glob("*")) {
    if(-d $file) {
      getFiles($dir . "/" . $file, $fileList); # full relative path saved
    } else {
      $fileList{$dir . "/" . $file}++;         # only files are put into list
    }
  }
}
# get the files list
my $filesA = getFiles($dirA);
my $filesB = getFiles($dirB);
# check them by using the keys from the 2 lists created.

相关内容

  • 没有找到相关文章

最新更新