代码之家  ›  专栏  ›  技术社区  ›  Zain Rizvi viperguynaz

如何在Perl中区分文件和目录?

  •  18
  • Zain Rizvi viperguynaz  · 技术社区  · 16 年前

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

    我该怎么区分呢?

    6 回复  |  直到 10 年前
        1
  •  30
  •   Paul Dixon    16 年前

    你可以使用 -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 manual page for more

    同时,尝试使用 File::Find 它可以为您重复使用目录。下面是一个查找目录的示例…

    sub wanted {
         if (-d) { 
             print $File::Find::name." is a directory\n";
         }
    }
    
    find(\&wanted, $mydir);
    
        2
  •  21
  •   Robert Gamble    16 年前
    print "$file is a directory\n" if ( -d $file );
    
        3
  •  10
  •   szabgab Brandon Fosdick    10 年前

    看看-x操作符:

    perldoc -f -X
    

    对于目录遍历,请使用file::find,或者,如果您不是受虐狂,请使用my 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
    

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

        4
  •  5
  •   skiphoppy    16 年前
    my @files = grep { -f } @all;
    my @dirs = grep { -d } @all;
    
        5
  •  4
  •   jonathan-stafford    16 年前
    我的$dh=opendir(“.”);
    my@entries=grep!/^?美元/,readdir($dh);
    关闭DH;
    
    foreach我的$entry(@entries){
    如果(-f$条目){
    #$entry是一个文件
    }ELSIF(-d$entry){
    #$entry是一个目录
    }
    }
    
        6
  •  2
  •   catfood    16 年前

    它会更容易使用 File::Find .