如何在Perl中查看目录是否存在?

Nan*_* HE 52 directory perl file-io

要在使用文件之前查看文件是否存在,我们可以使用:

if (-e "filename.cgi")
{
 #proceed with your code
} 
Run Code Online (Sandbox Code Playgroud)

但是如何识别目录是否存在?

Bra*_*ace 94

使用-d(文件测试的完整列表)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}
Run Code Online (Sandbox Code Playgroud)

作为注释,-e不区分文件和目录.要检查是否存在某些内容并且是纯文件,请使用-f.

  • @Peter - 虽然在技术上是正确的,但在生产代码中通常更好的做-e后跟-d,因此错误消息可以更有针对性.就生产中的问题解决而言,"不存在"和"作为非目录存在"之间存在差异. (9认同)
  • 如果你正在使用-d,那么你不需要-e(-d对于不存在的目录返回false). (3认同)