Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting names of directories under given path

Tags:

perl

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?

like image 365
Night Walker Avatar asked Nov 27 '22 02:11

Night Walker


2 Answers

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;
like image 108
innaM Avatar answered Dec 13 '22 22:12

innaM


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]/*");
like image 27
FMc Avatar answered Dec 14 '22 00:12

FMc