Nishi Bhonsle wrote:
>
> If I am still using the below logic, how can i modify the below prog
> to ignore empty directories and list only directories containing
> directories
> and files in buildlist.txt ?
>
> opendir DIR, $path or die "Can't open $path: $!";
>
>  #my @new = grep /[^.]/, readdir DIR;
>  my @new = grep { $_ ne "." and $_ ne ".." } readdir DIR;
>  closedir DIR;
>
>  open FILE,">>C:\buidlist.txt";
>  print FILE "$_\n" foreach @new;
>  close FILE;

Hi Nishi

To check whether a directory's empty or not you need to read /that/ directory in
turn. Since you'll be doing it twice it may as well go into a subroutine:

  use strict;
  use warnings;

  my $path = 'C:\data';

  my @new = grep { -d and dirlist($_) } dirlist($path);

  open my $fh,">> C:\\buildlist.txt";
  print $fh "$_\n" foreach @new;
  close $fh;

  sub dirlist {
    my $path = shift;
    opendir my $dh, $path or die "Can't open $path: $!";
    my @dir = grep { $_ ne "." and $_ ne ".." } readdir $dh;
    closedir $dh;
    map "$path\\$_", @dir;
  }


The subroutine dirlist() reads the directory, removes '.' and '..', and adds the
original path to each filename to return a list of the full paths to the
directory contents. The program calls dirlist() on the original path and uses
grep() to retain only those elements that are non-empty directories by using -d
and a further call to dirlist().

By the way, please 'use strict' and 'warnings' and use lexical variables like
this in your software so as to minimise the risk of simple mistakes.

HTH,

Rob


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to