Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 942
Zain Rizvi Avatar asked Oct 15 '08 20:10

Zain Rizvi


People also ask

How do I get the directory of a file in Perl?

The dirname() method in Perl is used to get the directory of the folder name of a file.

How do I view the contents of a directory?

Use the ls command to display the contents of a directory. The ls command writes to standard output the contents of each specified Directory or the name of each specified File, along with any other information you ask for with the flags.

What does file mean in Perl?

A filehandle is an internal Perl structure that associates with a file name. Perl File handling is important as it is helpful in accessing file such as text files, log files or configuration files. Perl filehandles are capable of creating, reading, opening and closing a file.


1 Answers

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);
like image 110
Paul Dixon Avatar answered Oct 01 '22 03:10

Paul Dixon