user2570205 user2570205 - 3 months ago 9
Perl Question

Find files matching pattern in the file array

I have code in perl as below. Trying pick files which matches the pattern.

opendir ERR_STAGING_DIR, "$ERR_STAGING" or die "$PID: Cannot open directory $ERR_STAGING";
@allfiles = grep !/^$ERR_STAGING\/\./, map "$ERR_STAGING/$_", readdir(ERR_STAGING_DIR);
closedir(ERR_STAGING_DIR);

$ERR_FILETYPE = basename ($ERR_FILETYPE);

$ERR_FILETYPE =~ s/\./\\\./g;
$ERR_FILETYPE =~ s/\*/\*/g;

@file_type = grep /^$ERR_STAGING/./$ERR_FILETYPE$/, @allfiles;
$numelements = @file_type;
if ($numelements <= 0) {
print LOG "$PID: No files match specified pattern, exiting.\n";
&HandlerDie($NO_FILE_TYPE, $current_poid);
}


Here is what I'm doing above. Grep all files from ERR_STAGING directory. grep files matching pattern
'BVN*.fin.bc_lerr.xml.bc'
e.g
BVN_201608250000.fin.bc_lerr.xml.bc
and do something with the file. However the above code is returning files which doesn't match pattern too, it also pickup some temp directories.

Answer

Correct two rows:

$ERR_FILETYPE =~ s/\*/.\*/g;                      # Add DOT

@file_type = grep /\/$ERR_FILETYPE$/, @allfiles;  # such a filter is sufficient