Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the list of subdirectories (only top level) in a directory using Perl

Tags:

perl

I would like to run a perl script to find only the subdirectories in a directory. I would not like to have the "." and ".." returned.

The program I am trying to use looks like this:

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 output of this however, has the "." and "..". How do I exclude them from the list?

like image 986
Sundar Avatar asked Apr 22 '11 02:04

Sundar


2 Answers

next unless $name =~ /^\.\.?+$/;

Also, the module File::Find::Rule makes a vary nice 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/^\.\.?$/);
like image 50
SymKat Avatar answered Sep 19 '22 00:09

SymKat


If you want to collect the dirs into an array:

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

If you really just want to print the dirs, you can do:

print "$_\n" foreach grep {-d "$root/$_" && ! /^\.{1,2}$/} readdir($dh);
like image 43
Sam Choukri Avatar answered Sep 22 '22 00:09

Sam Choukri