【问题标题】:How to check if a file with a .txt extension exists in a directory?如何检查目录中是否存在扩展名为 .txt 的文件?
【发布时间】:2012-08-21 00:34:17
【问题描述】:

我想知道如何检查目录中是否有带有.txt 扩展名的文件。

怎么做?

【问题讨论】:

    标签: perl file-exists


    【解决方案1】:

    只需使用 glob :

    if ( <*.txt> ) { ... }
    

    【讨论】:

    • ...或者由于人们习惯于看到用于从文件中读取的尖括号,glob('*.txt') 做了几乎完全相同的事情,同时更不容易出错。
    【解决方案2】:
    #! /usr/bin/perl
    
    my $dir = '.';  # current dir
    
    opendir(DIRHANDLE, $dir) || die "Couldn't open directory $dir: $!\n";
    my @txt = grep {  /\.txt$/ && -f "$dir/$_" } readdir DIRHANDLE;
    closedir DIRHANDLE;
    
    print ".txt files found" if (scalar(@txt));
    

    作为奖励,找到的所有 .txt 文件都在数组 @txt 中。

    【讨论】:

    • 不需要scalarprint ".txt files found" if @txt 好很多
    【解决方案3】:

    请记住,*.txt 实际上可能是一个目录。如果是你要的文件,grepglob:

    if ( grep -f, glob '*.txt' ) { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-20
      • 2011-04-20
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2011-04-27
      相关资源
      最近更新 更多