Perlのファイルをディレクトリと区別するにはどうすればよいですか?
質問
Perlの現在のディレクトリのすべてのサブディレクトリを走査し、それらのファイルからデータを取得しようとしています。 grepを使用して、指定されたディレクトリ内のすべてのファイルとフォルダーのリストを取得していますが、返される値のどれがフォルダー名で、どれがファイル拡張子のないファイルであるかわかりません。
どうやって違いを見分けることができますか?
解決
-d ファイルテスト演算子を使用して、何かがディレクトリであるかどうかを確認できます。一般的に有用なファイルテスト演算子の一部を次に示します
-e File exists. -z File has zero size (is empty). -s File has nonzero size (returns size in bytes). -f File is a plain file. -d File is a directory. -l File is a symbolic link.
詳細については、 perlfuncのマニュアルページ
をご覧ください。また、 File :: Find はディレクトリを再帰することができます。ディレクトリを探すサンプルを次に示します。...
sub wanted {
if (-d) {
print $File::Find::name." is a directory\n";
}
}
find(\&wanted, $mydir);
他のヒント
print "$file is a directory\n" if ( -d $file );
-X演算子を見てください:
perldoc -f -X
ディレクトリトラバーサルには、File :: Findを使用します。または、マゾヒストでない場合は、File :: Nextモジュールを使用します。実際、File :: Nextにファイルのみを返させ、ディレクトリを無視させることができます。
use File::Next;
my $iterator = File::Next::files( '/tmp' );
while ( defined ( my $file = $iterator->() ) ) {
print $file, "\n";
}
# Prints...
/tmp/foo.txt
/tmp/bar.pl
/tmp/baz/1
/tmp/baz/2.txt
/tmp/baz/wango/tango/purple.txt
my @files = grep { -f } @all;
my @dirs = grep { -d } @all;
my $dh = opendir("."); my @entries = grep !/^\.\.?$/, readdir($dh); closedir $dh; foreach my $entry (@entries) { if(-f $entry) { # $entry is a file } elsif (-d $entry) { # $entry is a directory } }
File :: Find
を使用する方が簡単です。
所属していません StackOverflow