如何区分文件与Perl中的目录?

Zai*_*zvi 19 directory perl file

我正在尝试遍历Perl中当前目录的所有子目录,并从这些文件中获取数据.我正在使用grep获取给定目录中所有文件和文件夹的列表,但我不知道返回的值是文件夹名称,哪个是没有文件扩展名的文件.

我怎么能分辨出来呢?

Pau*_*xon 31

您可以使用-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);
Run Code Online (Sandbox Code Playgroud)


Rob*_*ble 21

print "$file is a directory\n" if ( -d $file );
Run Code Online (Sandbox Code Playgroud)


And*_*ter 10

看看-X运算符:

perldoc -f -X
Run Code Online (Sandbox Code Playgroud)

对于目录遍历,使用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
Run Code Online (Sandbox Code Playgroud)

它位于http://metacpan.org/pod/File::Next


jon*_*ord 5

我的 $dh = opendir(".");
我的@entries = grep !/^\.\.?$/, readdir($dh);
关闭 $dh;

foreach 我的 $entry (@entries) {
    if(-f $entry) {
        # $entry 是一个文件
    } elsif (-d $entry) {
        # $entry 是一个目录
    }
}


ski*_*ppy 5

my @files = grep { -f } @all;
my @dirs = grep { -d } @all;
Run Code Online (Sandbox Code Playgroud)