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.
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
or readdir
for both directories, but not both. In this case glob
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
.
use strict;
use warnings;
use File::Basename;
my $f1 = 'data';
my $f1 = 'data/testroot';
my $ind = 6;
foreach (glob "$f1/*.hdf") {
my $patt = substr(basename($_), 0, $ind);
my @match = glob "$f2/$patt*.hdf";
#other code follows.......
}
${patt}*\\.hdf
means "0 or more occurrences of $patt, followed by .hdf". Are you sure you don't mean "$patt, followed by arbitrary text, followed by .hdf"?
That would be /${patt}.*\\.hdf/
.
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.