I am doing some testing where I have a lot of files that I need to perform data analysis on. We have a naming convention with our files, but sometime someone will add a little more to the file name. I'm looking for a way to look for the "core" of the name and then save the entire file name.
For example, I want to find WIRA_Rabcd_RT
, but someone may have saved th开发者_JAVA百科e file name as RED_GREEN_BLUE_WIRA_Rabcd_RT.txt
, so my folder will look something like this:
RED_GREEN_BLUE_WIRB_Rabcd_RT.txt
RED_GREEN_BLUE_WIRC_Rabcd_RT.txt
RED_GREEN_BLUE_WIRA_Rabcd_RT.txt ← I want to find this file, and open it.
RED_GREEN_BLUE_WIRF_Rabcd_RT.txt
RED_GREEN_BLUE_WIRG_Rabcd_RT.txt
RED_GREEN_BLUE_WIRT_Rabcd_RT.txt
RED_GREEN_BLUE_WIRW_Rabcd_RT.txt
RED_GREEN_BLUE_WIRQ_Rabcd_RT.txt
The glob function seems like it would do the trick:
my $dir = '/some/directory/';
my @files = glob($dir . '*WIRA_Rabcd_RT.txt');
# Make sure you get exactly one file, open it, etc.
In Perl TIMTOWTDI
so here is another way:
#!/usr/bin/perl
use strict;
use warnings;
my $dir = 'dirname';
my $pattern = 'WIRA_Rabcd_RT';
my @files;
{
opendir my $dir_handle, $dir;
@files = grep { /$pattern/ } readdir $dir_handle;
} #end-of-block autocloses lexical $dir_handle
@files
now contains the names of the files in the directory that matches the pattern. Note that the names are relative to that directory (stored as name
not dir/name
). I often then use the File::chdir
module to change the working directory to $dir
to work on those files. For example:
use File::chdir
# get @files in $dir as above...
{
local $CWD = $dir;
# work with files in @files
}
# working directory restored to original here
精彩评论