How do I distinguish a file from a directory in Pe

2020-02-26 04:54发布

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?

6条回答
来,给爷笑一个
2楼-- · 2020-02-26 05:20

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);
查看更多
ゆ 、 Hurt°
3楼-- · 2020-02-26 05:20

It would be easier to use File::Find.

查看更多
爷、活的狠高调
4楼-- · 2020-02-26 05:23
my @files = grep { -f } @all;
my @dirs = grep { -d } @all;
查看更多
戒情不戒烟
5楼-- · 2020-02-26 05:27

Look at the -X operators:

perldoc -f -X

For directory traversal, use File::Find, or, if you're not a masochist, use my File::Next module which makes an iterator for you and doesn't require crazy callbacks. In fact, you can have File::Next ONLY return files, and ignore directories.

use File::Next;

my $iterator = File::Next::files( '/tmp' );

while ( defined ( my $file = $iterator->() ) ) {
    print $file, "\n";
}

# Prints...
/tmp/foo.txt
/tmp/bar.pl
/tmp/baz/1
/tmp/baz/2.txt
/tmp/baz/wango/tango/purple.txt

It's at http://metacpan.org/pod/File::Next

查看更多
叼着烟拽天下
6楼-- · 2020-02-26 05:33
print "$file is a directory\n" if ( -d $file );
查看更多
乱世女痞
7楼-- · 2020-02-26 05:41
my $dh = opendir(".");
my @entries = grep !/^\.\.?$/, readdir($dh);
closedir $dh;

foreach my $entry (@entries) {
    if(-f $entry) {
        # $entry is a file
    } elsif (-d $entry) {
        # $entry is a directory
    }
}
查看更多
登录 后发表回答