How can I open a file in Perl using a wildcard in the directory name?

拟墨画扇 提交于 2019-12-14 01:26:46

问题


I need to open a file called OrthologousGroups.txt from a directory that is named based on the date of when it is created. e.g. ./Results_2016-2-7

Is there a way to use a wildcard in the path name to the file I need to access?

I tried the following

open(FILE, "./Results*/OrthologousGroups.txt");

but I get an error

readline() on closed filehandle


回答1:


Use glob to get a list of filenames matching the glob pattern:

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

As a general note, you should check whether open succeeded, instead of simply assuming it did, then you won't get "readline on closed filehandle" errors when you didn't actually open a file in the first place.



来源:https://stackoverflow.com/questions/35471597/how-can-i-open-a-file-in-perl-using-a-wildcard-in-the-directory-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!