lyon
lyon

Reputation: 23

How can I iterate over array and get the count of matches?

I'm trying to check if inside a directory there's the number of files that I expect. I need to check if the files match the regex that I pass. I pass and split the string of regex to an array, can anyone help me? Thanks

my $dir = 'C:\Users\dealmeidal\Desktop\perl_file';
my $string = '3-qr/Clawbacks_20190421\.csv$/-qr/Premiums_20190421\.csv$/-qr/Polizza_20190421\.csv$/';
my @array_regex_tot = (split /-/, $string);
my $expected_file_num = int(shift(@array_regex_tot));
my $file_counter = 0;
checkFilesInDirectory($dir, \@array_regex_tot, $expected_file_num);

sub checkFilesInDirectory {
    my ($dir_path, $array_reg, $file_previsti) = @_;
    opendir (DIR, $dir_path)  or die "Can't open $dir_path: $!";
   foreach my $file (@file) {
         foreach my $regex (@$array_reg) {
             if ($file =~ $regex) {
                $file_counter++;
            }
        } 
    }
    if ($file_counter < $expected_file_num) {
        print "KO. Less files than expected.\n";
    } elsif ($file_counter == $expected_file_num) {
        print "OK Correct num of files\n";
    } elsif ($file_counter > $expected_file_num) {
        print "WARNING More files than expected.\n";
    }
    closedir(DIR);
}

Upvotes: 1

Views: 68

Answers (1)

simbabque
simbabque

Reputation: 54381

The problem is that you can't have actual Perl code inside the pattern. What you're getting is Perl commands to create precompiled patterns, not patterns. So the qr// bit is treated as literal in your match. You'll see that by turning on regex debugging:

use re 'debug';

my $pattern = 'qr/Clawbacks_20190421\.csv$/';
'Clawbacks_20190421.csv' =~ $pattern;

This'll output:

Compiling REx "qr/Clawbacks_20190421\.csv$/"
Final program:
   1: EXACT <qr/Clawbacks_20190421.csv> (9)
   9: SEOL (10)
  10: EXACT </> (12)
  12: END (0)
anchored "qr/Clawbacks_20190421.csv"$ at 0 (checking anchored) minlen 26 
Freeing REx: "qr/Clawbacks_20190421\.csv$/"

As you can see, the qr/ and / are part of the pattern, and that will not match your filename. If you can't change the input string, you will have to clean up.

my $pattern = 'qr/Clawbacks_20190421\.csv$/';
$pattern =~ m{^qr/(.+)/};
my $clean = $1;

'Clawbacks_20190421.csv' =~ $clean;

We use a different delimiter here to not have to escape the slashes.

Upvotes: 1

Related Questions