如何在目录名中使用通配符在Perl中打开文件?

tki*_*der 3 perl

我需要打开一个OrthologousGroups.txt从一个目录调用的文件,该目录是根据创建它的日期命名的.例如./Results_2016-2-7

有没有办法在路径名中使用通配符来访问我需要访问的文件?

我尝试了以下内容

open(FILE, "./Results*/OrthologousGroups.txt");
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误

关闭文件句柄上的readline()

hob*_*bbs 6

使用glob得到的glob模式匹配的文件名列表:

my @files = glob "./Results*/OrthologousGroups.txt";

if (@files != 1) {
    # decide what to do here if there are no matching files,
    # or multiple matching files
}

open my $fh, $files[0] or die "$! opening $files[0]";

# do stuff with $fh
Run Code Online (Sandbox Code Playgroud)

作为一般说明,您应该检查open是否成功,而不是简单地假设它已经成功,那么当您实际上没有首先打开文件时,您将不会获得"readline on closed filehandle"错误.

  • OP没有说,但我认为这可能是Windows的一个问题,在这种情况下`使用File :: Glob':bsd_glob'`对于处理文件路径中的空格很重要 (4认同)