user553702
user553702

Reputation: 2935

Perl: How to glob all and only subdirectories?

I am trying to write a Perl script that does a preorder directory traversal. I need it to get all subdirectories of a given directory including the hidden ones. Unfortunately when I try to glob this way:

<$dir/* $dir/.*>

... the ".*" causes "." and ".." to be returned too, and this messes up my function because it causes an infinite loop. How do I get only the subfolders of $dir, both regular and hidden, and not the current or upper-level directory?

For example if my folder is "dir" and it contains these subdirectories:

hello
.hiddendir
"dir with space in name"
".hidden dir with space in name"
dir2

... I want to get an array with just these and not "." or "..".

I don't care if files show up too because I use "if (-d $dir)" later. Is there a way I can test whether an element of the globbed array is equal to the current directory or the parent directory so I can exclude them?

Thanks

Upvotes: 0

Views: 4233

Answers (3)

toolic
toolic

Reputation: 62105

The read_dir function in File::Slurp automatically excludes . and .., by default.

Upvotes: 1

ikegami
ikegami

Reputation: 385935

perl -MFile::Find::Rule -E'
   say
      for
         File::Find::Rule->directory->in(".");'

or

perl -MFile::Find::Rule -E'
   say
      for
          grep $_ ne ".",
             File::Find::Rule->directory->in(".");'

File::Find::Rule

Upvotes: 5

Eddie
Eddie

Reputation: 939

Just use grep to filter out the . and .. directories:

grep { !/^\.{1,2}$/ } <$dir/* $dir/.*>

Upvotes: 1

Related Questions