2012-05-23 3 views
1

현재 두 디렉토리의 파일을 비교하고 각 파일에서 변경된 기능을 표시하는 프로그램을 작성 중입니다. 그러나, 나는 디렉토리에 무엇이 파일인지 또는 서브 디렉토리인지를 검사 할 때 문제가 발생했다. 지금은 단순히 그것이 -d 체크가있는 디렉토리인지를 점검 할 때 서브 디렉토리를 잡아 내지 못합니다. 아래에 제 코드의 일부를 게시했습니다.Perl : 입력이 파일인지 디렉토리인지 확인

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"; 
    } 
} 

어떤 도움을 주셔서 감사합니다!

+0

두 가지 :;'사용 경고 '와, 1 bareword는 핸들이 나쁜 (물론, 당신은 당신이'엄격한 사용하기 때문에이 들었다' * right *?), 2. 왜 디렉토리 핸들의'readdir'에서'grep {-f $ _}'을하지 않으십니까? –

+0

나는 사용 영역을 사용한다; 경고를 사용하십시오. grep {-f $ _}을 사용하려고했을 때 perl 파일을 제외한 모든 파일을 읽지 않습니다. – Kat

+0

그런 다음 시작하십시오. 버려진 원 - 라이너를 쓰지 않는다면, 쓰는 Perl 코드의 모든 단일 비트에서'엄격한 사용'과'경고 사용'을 사용해야합니다. –

답변

6

perldoc -f readdir로 상태 :

당신은 당신이 더 문제가되는 디렉토리를 앞에 추가 것 readdir을, 밖으로 반환 값을 파일 테스트 계획이라면. 그렇지 않으면, 우리는 이 거기 chdir 않았기 때문에, 그것은 잘못된 파일을 테스트했을 것입니다.

if(-d "$newDir/$_") { 
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. 
3

사용 Path::Class

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


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