tags:

views:

219

answers:

4

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 files matching above given pattern.

+2  A: 

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_}))
codaddict
Venkat doesn't know the entire filename, just the first 5 characters, according to the question as it stands now (edited by you?). This doesn't seem to solve his problem.
jimtut
+3  A: 

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.

Sinan Ünür
+8  A: 

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.

toolic
A: 

How about

foreach $f (</d1/d2/d3/*.dat>) {if ($f =~ /\w{4}_\d{5}_\d{5}\.dat/)  {print $f}};
Mike Warner
Angle brackets with an * is just syntactic sugar for glob. The explicit approach is cleaner.
jmanning2k