Listing subdirectories (top level only) in a directory using Perl

I would like to run a perl script to find only subdirectories in a directory. I would not want to have a "." and ".." is back.

The program I'm trying to use is as follows:

use warnings; use strict; my $root = "mydirectoryname"; opendir my $dh, $root or die "$0: opendir: $!"; while (defined(my $name = readdir $dh)) { next unless -d "$root/$name"; print "$name\n"; } 

The result of this, however, is ".". and "..". How can I exclude them from the list?

+7
source share
4 answers

If you want to collect dirs into an array:

 my @dirs = grep {-d "$root/$_" && ! /^\.{1,2}$/} readdir($dh); 

If you really want to print directories, you can do:

 print "$_\n" foreach grep {-d "$root/$_" && ! /^\.{1,2}$/} readdir($dh); 
+12
source
 next unless $name =~ /^\.\.?+$/; 

In addition, the File :: Find :: Rule module makes an excellent interface for this type of thing.

 use File::Find::Rule; my @dirs = File::Find::Rule->new ->directory ->in($root) ->maxdepth(1) ->not(File::Find::Rule->new->name(qr/^\.\.?$/); 
+8
source

Just change your check to find out when $ name equals '.' or ".." and skip the recording.

+4
source

File :: Slurp read_dir automatically excludes special point directories (and ..) for you. You do not need to get rid of them explicitly. It also checks for opening your directory:

 use warnings; use strict; use File::Slurp qw(read_dir); my $root = 'mydirectoryname'; for my $dir (grep { -d "$root/$_" } read_dir($root)) { print "$dir\n"; } 
+1
source

All Articles