2010-12-20 34 views
47

要查看是否有文件中使用它之前就存在,我们可以使用:如何查看Perl中是否存在目录?

if (-e "filename.cgi") 
{ 
#proceed with your code 
} 

但如何indentify一个目录存在与否?

+1

大约一半的Perl问题涉及非常基本的主题。如果你读了一些书,你可以节省一些时间。 [Perl语言入门④](http://oreilly.com.cn/book.php?bn=978-7-5641-0636-2),[学习Perl⑤](http://oreilly.com/catalog/ 9780596520113 /) – daxim 2010-12-20 08:49:36

+29

我猜他花了很少的时间来问这些问题,并且他们是非常有用的搜索结果。不要成为一个学习风格偏执。 – 2012-09-13 21:27:39

+1

@Adam我认为daxim的观点只是OP的perl问题(包括这一个)都是非常基础的,所以阅读perl的概述可能会节省一些时间,并提出很多具体问题的答案很容易找到其他方式 – GreenGiant 2013-09-25 23:11:43

回答

85

使用-dfull list of file tests

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 
} 

作为一个说明,-e没有文件和目录进行区分。要检查是否存在并且是纯文件,请使用-f

+3

如果您使用-d,那么您不需要-e(-d为不存在的目录返回false)。 – 2010-12-20 04:53:50

+9

@Peter - 虽然在技术上是正确的,但在生产代码中,通常最好先执行-e后跟-d,这样错误消息就可以更有针对性。就生产中的问题解决而言,“不存在”和“作为非目录存在”是有区别的。 – DVK 2010-12-20 15:00:51

相关问题