user3781528 user3781528 - 1 year ago 82
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"
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";


Is there another method to check if
file exists in each folder of
? Thanks

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download