I am trying to get the names of all first level directories under given path.
I tried to use File::Find but had problems.
Can someone help me with that?
Use the-d
file check operator:
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
my $path = $ARGV[0];
die "Please specify which directory to search"
unless -d $path;
opendir( my $DIR, $path );
while ( my $entry = readdir $DIR ) {
next unless -d $path . '/' . $entry;
next if $entry eq '.' or $entry eq '..';
print "Found directory $entry\n";
}
closedir $DIR;
If you don't need to traverse the entire directory hierarchy, File::Slurp is much easier to use than File::Find.
use strict;
use warnings;
use File::Slurp qw( read_dir );
use File::Spec::Functions qw( catfile );
my $path = shift @ARGV;
my @sub_dirs = grep { -d } map { catfile $path, $_ } read_dir $path;
print $_, "\n" for @sub_dirs;
And if you ever do need to traverse a hierarchy, check CPAN for friendlier alternatives to File::Find
.
File::Finder and File::Find::Rule are front-ends for File::Find
.
File::Find::Closures is worth studying to learn how to use File::Find
and how
to write closures.
File::Next uses an iterator approach to directory traversal and looks promising, although I have never used it.
Finally, in the spirit of TIMTOWTDI, here's something quick and sleazy:
my @sub_dirs = grep {-d} glob("$ARGV[0]/*");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With