Can I do something like this in Perl? Meaning pattern match on a file name and check whether it exists.
if(-e "*.file")
{
#Do something
}
I know the longer solution of asking system to list the files present; read it as a file and then infer whethe开发者_运维技巧r file exists or not.
You can use glob
to return an array of all files matching the pattern:
@files = glob("*.file");
foreach (@files) {
# do something
}
If you simply want to know whether a file matching the pattern exists, you can skip the assignment:
if (glob("*.file")) {
# At least one file matches "*.file"
}
On Windows I had to use File::Glob::Windows as the Windows path separating backslashes don't seem to work perl's glob.
On *nix systems, I've used the following with good results.
sub filesExist { return scalar ( my @x = `ls -1a 2> /dev/null "$_[0]"` ) }
It replies with the number of matches found, or 0 if none. Making it easily used in 'if' conditionals like:
if( !filesExist( "/foo/var/not*there.log" ) &&
!filesExist( "/foo/var/*/*.log" ) &&
!filesExist( "/foo/?ar/notthereeither.log" ) )
{
print "No matches!\n";
} else {
print "Matches found!\n";
}
Exactly what patterns you could use would be determined by what your shell supports. But most shells support the use of '*' and '?' - and they mean the same thing everywhere I've seen. Of course, if you removed the call to the 'scalar' function, it would return the matches - useful for finding those variable file names.
精彩评论