我正在尝试遍历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 ONLY返回文件,并忽略目录。

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

http://metacpan.org/pod/File::Next

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

会更容易
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top