File name matching with -e and regular expressions in perl
I need to check for the existence of a file in a directory. The file name has a pattern like:
/d1/d2/d3/abcd_12345_67890.dat
In my program, I will know the file name up to abcd_
I need to write an if
condition using -e
option and find the fi开发者_StackOverflow中文版les matching above given pattern.
You can use glob to return a list of existing files whose name matches a pattern:
my @files = glob '/d1/d2/d3/abcd_*.dat';
In this case, there is no need to perform the -e
filetest.
You cannot use -e
for partial file name matches.
use File::Basename;
use File::Slurp;
my ($name, $path) = basename('/d1/d2/d3/abcd_');
my $exists = grep { /^\Q$name\E_[0-9]{5}_[0-9]{5}\.dat\z/ } read_dir $path;
If the directory contains a lot of files, you can still keep your program's footprint constant by using opendir and using readdir in a while loop.
I used File::Slurp::read_dir
here to present an uncluttered solution.
If I understand your question correctly, you want to check if the file exists and the filename has a particular format. If this is what you want you can do this:
use File::Basename;
$file = "/d1/d2/d3/abcd_12345_67890.dat";
print "SUCCESS" if(-e $file and (basename($file)=~m{^abcd_}))
How about
foreach $f (</d1/d2/d3/*.dat>) {if ($f =~ /\w{4}_\d{5}_\d{5}\.dat/) {print $f}};
精彩评论