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

后端 未结 6 1118
天涯浪人
天涯浪人 2020-12-31 01: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 folder

相关标签:
6条回答
  • 2020-12-31 02:00
    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
        }
    }
    
    0 讨论(0)
  • 2020-12-31 02:03
    my @files = grep { -f } @all;
    my @dirs = grep { -d } @all;
    
    0 讨论(0)
  • 2020-12-31 02:07

    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

    0 讨论(0)
  • 2020-12-31 02:11

    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);
    
    0 讨论(0)
  • 2020-12-31 02:16
    print "$file is a directory\n" if ( -d $file );
    
    0 讨论(0)
  • 2020-12-31 02:19

    It would be easier to use File::Find.

    0 讨论(0)
提交回复
热议问题