surajsam has asked for the wisdom of the Perl Monks concerning the following question:

It may appear like a FAQ but did not find the one that would help me. Hence the question. There is only one subdir within a directory and the rest are files. How can I grab the subdir and its contents ? The problem is readdir returns the files and not more than that. I tried "grep {-d}" and all. It is of no use. How to get the subdir ?

Replies are listed 'Best First'.
Re: finding a subdir
by toolic (Bishop) on Dec 03, 2011 at 04:44 UTC
    Make sure you prepend the dir when using readdir
    grep { -d "$dir/$_" } readdir $dh;
Re: finding a subdir
by Khen1950fx (Canon) on Dec 03, 2011 at 05:20 UTC
    You could use find2perl:
    find2perl /tmp -type d
    which gives you:
    #!/usr/bin/perl use strict; use warnings; use File::Find (); use vars qw/*name *dir/; *name = *File::Find::name; *dir = *File::Find::dir; sub wanted; File::Find::find({wanted => \&wanted}, '/tmp'); exit; sub wanted { my ($dev, $ino, $mode, $nlink, $uid, $gid); (($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_)) && -d && print ("$name\n"); }
    Adjust as necessary.
Re: finding a subdir
by Anonymous Monk on Dec 03, 2011 at 04:03 UTC

    It may appear like a FAQ but did not find the one that would help me. Hence the question. There is only one subdir within a directory and the rest are files. How can I grab the subdir and its contents ? The problem is readdir returns the files and not more than that. I tried "grep {-d}" and all. It is of no use. How to get the subdir ?

    Well, that should work, so show what you tried , and we'll fix it for ya :)

    Alternatively, see File::Find::Rule/Path::Class::Rule, and example of each

Re: finding a subdir
by TJPride (Pilgrim) on Dec 03, 2011 at 10:13 UTC
    Not sure what precisely you're trying to do, but here's something for spidering a directory and its contents:

    use strict; use warnings; my @f = ('/perltest/folder/'); my ($folder, $file); do { $folder = shift @f; opendir(DIR, $folder); while ($file = readdir(DIR)) { next if $file =~ /\.$/; ### Skip . and .. if (-d "$folder$file") { print "$folder$file/ is a directory.\n"; push @f, "$folder$file/"; next; } print "$folder$file is a file.\n"; } } while ($#f != -1);