Search code examples
perlfiledirectory

How do I distinguish a file from a directory in Perl?


I'm trying to traverse through all the subdirectories of the current directory in Perl, and get data from those files. I'm using grep to get a list of all files and folders in the given directory, but I don't know which of the values returned is a folder name and which is a file with no file extention.

How can I tell the difference?


Solution

  • You can use a -d file test operator to check if something is a directory. Here's some of the commonly useful file test operators

        -e  File exists.
        -z  File has zero size (is empty).
        -s  File has nonzero size (returns size in bytes).
        -f  File is a plain file.
        -d  File is a directory.
        -l  File is a symbolic link.
    

    See perlfunc manual page for more

    Also, try using File::Find which can recurse directories for you. Here's a sample which looks for directories....

    sub wanted {
         if (-d) { 
             print $File::Find::name." is a directory\n";
         }
    }
    
    find(\&wanted, $mydir);