user3781528 user3781528 - 2 days ago 4
Perl Question

Perl check if filename matching a pattern exists recursevely

I'm looping through folders in a directory and need to check if a file that matches a pattern exists in each directory. I've used glob but it seems to work for the the first folder only. I get file not found for the second folder even I know that it's there.

Here is my code:

my @dirs = grep { -d } glob '/data/test_all_runs/*';

for my $dir ( @dirs ) {

print "the directory is $dir\n";
my $run_folder = (split '/', $dir)[3];
print "the folder is $run_folder\n";

my $matrix_excel = $dir."/*bcmatrix.xls";
my $summary_excel = $dir."/*bc_summary.xls";

unless (-e $summary_excel) {
if (glob($summary_excel)) {
At least one file matches "*.file"
}
else
{
print "File Doesn't Exist!";
print STDERR "|=============================================|\n";
print STDERR "| |\n";
print STDERR "| Can't find Summary .xls File!!! |\n";
print STDERR "| |\n";
print STDERR "| Upload the file and rerun the program. |\n";
print STDERR "| |\n";
print STDERR "|=============================================|\n";

die;
}
}


Is there another method to check if
*bcmatrix.xls
file exists in each folder of
/data/test_all_runs/*
? Thanks

Answer

I suggest that you use something like this. It will build a hash of arrays that lists all the files in each subdirectory of /data/test_all_runs that look like either *bcmatrix.xls or *bc_summary.xls

You should be able to do what you want with the result

use strict;
use warnings 'all';

use File::Spec::Functions 'splitdir';

my %files;

for my $path ( glob '/data/test_all_runs/*/*{bcmatrix,bc_summary}.xls' ) {

    my ($subdir, $file) = (splitdir $path)[-2, -1];

    push @{ $files{$subdir} }, $file;
}

use Data::Dumper;
print Dumper \%files;
Comments