1

私は現在、最終的に 2 つのディレクトリ内のファイルを比較し、各ファイルで変更された機能を表示するプログラムを作成しています。ただし、ディレクトリにあるものがファイルであるかサブディレクトリであるかを確認するときに問題が発生しました。現在、-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 compared\n\n";
    } elsif((File::Compare::compare("$newDir/$_", "$oldDir/$_") == 1)) {
        print "$_ in new directory $newDirName differs from old directory $oldDirName\n\n";
        print OUTPUTFILE "File: $_ has been update. Please check marked functions for differences\n";
        print OUTPUTFILE "\n\n";
        print OUTPUTFILE "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\n\n";
    } elsif((File::Compare::compare("$newDir/$_", "$oldDir/$_") < 0)) {
        print "$_ found in new directory $newDirName but not in old directory $oldDirName\n";
        print "Entire file not printed to output file but instead only file name\n";
        print OUTPUTFILE "File: $_ is a new file!\n\n";
        print OUTPUTFILE "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\n\n";
    }
 }

foreach (@allOldFiles) {
    if((File::Compare::compare("$newDir/$_", "$oldDir/$_") < 0)) {
        print "$_ found in old directory $oldDirName but not in new directory $newDirName\n\n";
    }
 }

助けてくれてありがとう!

4

3 に答える 3

6

perldoc -f readdirが述べているように:

readdirから戻り値をファイルテストすることを計画している場合は、問題のディレクトリの前に追加することをお勧めします。そうでなければ、そこでchdirを実行しなかったため、間違ったファイルをテストしていたでしょう。

if(-d "$newDir/$_") {
于 2012-05-23T19:53:12.190 に答える
3

パス::クラスを使用

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


my @allNewFiles = grep { !$_->is_dir } dir("/newDir")->children;
于 2012-05-23T20:00:49.850 に答える
1

再帰呼び出しを使用して、最初にファイルのリストを取得してから、それらを操作します。

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.
于 2012-05-23T19:51:33.620 に答える