I have a string stored in a Perl variable that should match with the beginning part of a file name stored in a directory.
I use this variable to find the file matching this pattern from the directory, using Perl's grep. Here's what I am doing:
opendir (DIR, "data/testroot/") or die "$!";
@file1 = <$f1/*.hdf>
foreach(@file1){
$patt = substr(basename($_),0,$ind);
$file2 = grep {/${patt}*\.hdf/} readdir(DIR);
#other code follows.......
}
closedir(DIR);
First, I get a list of all files in folder f1
and storing them in the array @file
. Then for each entry in @file1
, I extract the first few characters, store them in $patt
, then try to pick up similar files from another folder data/testroot/
which have the matching beginning pattern as stored in $patt
.
That grep $file2 = grep {/${patt}*\.hdf/} readdir(DIR);
is not working.
Best Answer
I think you want to find all
*.hdf
files in directory A whose filenames match the first$ind
characters of any such file in directory B?You should use either
glob
orreaddir
for both directories, but not both. In this caseglob
seems to be the best bet as it allows you to select all*.hdf
files from A without having to check them with the regex.The program below seems to do what you need. I have substituted sample values for
$f1
and$ind
.