Check for a file in the Perl directory

I know that you can check if the file is a directory using:

if(-d $filename) 

but how can you check if it is a directory?

+6
source share
4 answers

Have you thought of trying the following?

 if (! -d $filename) ... 

The result of -d is, after all, something that can be considered as a boolean, therefore a logical operator ! will work fine.

And if you use something more specific than "not a directory", see here . There are many things that are not directories, which sometimes do not make sense to consider as ordinary files.

Keep in mind that if you have already confirmed that the file name exists. If you follow ! -d ! -d in a nonexistent file name, it will return true.

This is a philosophical question about whether you consider a non-existent thing “not a catalog”, but if you want to provide it, you can use it ! -d ! -d combined with -e , something like:

 if ((-e $filename) && (! -d $filename)) ... 
+15
source

To verify that something is a file, but not a directory, you just need to combine the two tests (there is no single test):

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

Note:

  • With all due respect, paxdiablo's answer is incorrect for how the question is formulated (clean !-d does not work for what the user asked, checking if the random thing / line is not a directory, NOT is something a file that is not a directory) . For instance. !-d NO_SUCH_FILE returns true.

  • Greg’s answer may be correct depending on whether the original user should include non-regular files (for example, symbolic links, named pipes, etc.) in their definition of “file that is not a directory”. If they wanted to include all of these special “files,” Greg’s answer is also incorrect, since “-f” excludes them (as Greg generally noted in his answer).

+5
source

In the spirit of TIMTOWTDI :

 unless (-d $filename) 
+3
source

The -f statement checks if something is a "regular file". This excludes directories, but also excludes things like pipes and device nodes.

 if (-f $filename) { ... 
+2
source

Source: https://habr.com/ru/post/899014/


All Articles