File::Find 모듈을 사용하지 않는 이유는 무엇입니까? Perl 5.x부터 거의 모든 Perl 배포판에 포함되어 있습니다. 지저분한 방식으로 작동하는 것은 내가 좋아하는 모듈이 아니지만 좋은 일을합니다.
원하는 작업을 수행하고 원하지 않는 것을 필터링하는 wanted
서브 루틴을 정의합니다. 이 경우, 거의 모든 것을 인쇄하고 있으므로, 모두 wanted
은 찾은 것을 인쇄합니다.
File::Find
에는 파일 이름이 $File::Find::name
이고 해당 파일의 디렉터리는 $File::Find::dir
입니다. $_
은 파일 자체이므로 테스트에 사용할 수 있습니다.
여기 당신이 원하는 기본적인 방법 :
use strict;
use warnings;
use feature qw(say);
use File::Find;
my $directory = `/tmp/test`;
find (\&wanted, $directory);
sub wanted {
say $File::Find::Name;
}
내 find
서브 루틴 내 wanted
기능을 넣어 선호하는, 그래서 그들은 함께있어. 이것은 위와 동일합니다 :
use strict;
use warnings;
use feature qw(say);
use File::Find;
my $directory = `/tmp/test`;
find (
sub {
say $File::Find::Name
},
$directory,
);
좋은 프로그래밍은 서브 루틴에서 인쇄하지 않는다고 말합니다. 대신, 서브 루틴을 사용하여 데이터를 저장하고 반환해야합니다. 불행히도 find
은 전혀 반환하지 않습니다. 별도의 wanted
서브 루틴을 원하는 경우,
use strict;
use warnings;
use feature qw(say);
use File::Find;
my $directory = `/tmp/test`;
my @directory_list;
find (
sub {
push @directory_list, $File::Find::Name
}, $directory);
for my $file (@directory_list) {
say $file;
}
또는 : 당신은 그들을 인쇄 나중에 파일 목록을 캡처하는 글로벌 배열을 사용하고, 필요
use strict;
use warnings;
use feature qw(say);
use File::Find;
my $directory = `/tmp/test`;
my @directory_list;
find (\&wanted, $directory);
sub wanted {
push @directory_list, $File::Find::Name;
}
for my $file (@directory_list) {
say $file;
}
사실 그 내 원하는 서브 루틴은 서브 루틴에 국부적이지 않은 배열에 의존하기 때문에 내 find
호출 내에서 wanted
서브 루틴을 포함하는 것이 더 나은 이유입니다.
당신이 할 수있는 한 가지는 서브 루틴을 사용하여 원하는 것을 필터링하는 것입니다. 의 당신은 JPG 파일 만 관심이 있다고 가정 해 봅시다 : 원하는 서브 루틴 내 @directory_list
배열로 밀어 전에 원하지 않는 파일에 대한 next
어떻게하는지
use strict;
use warnings;
use feature qw(say);
use File::Find;
my $directory = `/tmp/test`;
my @directory_list;
find (\&wanted, $directory);
sub wanted {
next unless /\.jpg$/i; #Skip everything that doesn't have .jpg suffix
push @directory_list, $File::Find::Name;
}
for my $file (@directory_list) {
say $file;
}
참고. 다시 말하지만, 나는 삽입 선호 :이 당신이 무엇을 요구 정확히 아니라는 것을 알고
find (sub {
next unless /\.jpg$/i; #Skip everything that doesn't have .jpg suffix
push @directory_list, $File::Find::Name;
}
,하지만 당신은 아직 작성하지 않은 경우 그냥합니다 (Find::File
모듈에 대해 알려 펄 모듈을 소개하고 싶었다 Perl에 많은 기능을 추가 할 수있는 이들에 대해 알고 있어야한다.
'File :: Spec' <-이 모듈은'no_upwards()'func을 사용하여'.' 또는'..'와 같은 모든 디렉토리를 숨 깁니다. 예 :'@paths = File :: Spec-> no_upwards (@paths);' – gaussblurinc
'while (readdir ($ dir)) {...}'을 사용하기 때문에 프로그램에'use 5.012; 이전 릴리스에서는 작동하지 않습니다. –