my $dw = new File::DirWalk; sub on_dir_leave { $dw->{'depth_count'} == $depth and push @folder, shift; File::DirWalk::SUCCESS } $dw->onDirLeave( \&on_dir_leave ); $dw->setDepth( $depth + 1 ); $dw->walk( $_ ) for @directory;