开发者

Test if file is NOT a directory in Perl

开发者 https://www.devze.com 2023-04-11 21:55 出处:网络
I\'m aware you can test if a file is a directory using: if(-d $filen开发者_如何转开发ame) but how can you test if it\'s not a directory?Have you thought of trying the following?

I'm aware you can test if a file is a directory using:

if(-d $filen开发者_如何转开发ame)

but how can you test if it's not a directory?


Have you thought of trying the following?

if (! -d $filename) ...

The result of -d is, after all, something that can be treated as a boolean value, hence the logical not operator ! will work fine.

And, if you're after something more specific than "not a directory", see here. There are quite a few things that aren't directories that it sometimes doesn't make sense to treat as regular files.

Keep in mind that's assuming you've already validated that the filename exists. If you do a ! -d on a non-existent filename, it will return true.

It's a philosophical matter as to whether you consider a non-existent thing to be "not a directory" but, if you want to ensure it exists as well, you can use ! -d in conjunction with -e, something like:

if ((-e $filename) && (! -d $filename)) ...


To test if something is a file, BUT not a directory, you need to simply combine the 2 tests (there's no single test):

if (-e $file && !-d $file) { # a file but not a directory }

Please note that:

  • With all due respect, paxdiablo's answer is wrong for the way the question is worded ( pure !-d does not work for what the user asked as it checks if a random thing/string is not a directory, NOT whether something is a file which is not a directory). E.g. !-d NO_SUCH_FILE returns true.

  • Greg's answer may be correct depending entirely on whether the original user meant to include non-plain files (e.g. symbolic links, named pipes, etc..) in their definition of "file which is not a directory". If they meant to include all those special "files", Greg's answer is also wrong as "-f" excludes them (as Greg wisely noted in his answer in the first place).


In the spirit of TIMTOWTDI:

unless (-d $filename)


The -f operator tests to see whether something is a "regular file". This excludes directories, but also excludes such things as pipes and device nodes.

if (-f $filename) { ...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号