简体   繁体   中英

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

I need to open a file called OrthologousGroups.txt from a directory that is named based on the date of when it is created. eg ./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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM