collecting list of directories

They have: 447 posts

Joined: Oct 1999

heres my code:

@dirs = 'c:/';

foreach(@dirs)
{ opendir(DIR, $_);
@temp = readdir(DIR);
foreach $file(@temp)
{ $a = push(@dirs, $file) if -d $file; }
close(DIR);
}

open(OUTFILE, ">data.txt");
foreach(@dirs)
{ print OUTFILE "$_\n"; }

what im trying to do is get a list of all directories on the computer. i assume it doesnt work because when i start the foreach loop @dirs only holds one value and it doesnt take into account any values added to the array during the loop.

any ideas?

They have: 447 posts

Joined: Oct 1999

ok, one of my problems is the filetest operator is not working correctly.

@dirs = 'c:/';

foreach(@dirs)
{ opendir(DIR, $_);
@temp = readdir(DIR);
foreach $file(@temp)
{ push(@dirs, $file) if -d $file; }
close(DIR);
}

# push(@dirs, $file) if -d $file always returns false
# do file test operators now work on windows systems? if i change it to push(@dirs, $file) it works, but gives me all files and not just directories
push(@dirs, $file) if -e $file; should give me everything too, but gives me nothing.

They have: 447 posts

Joined: Oct 1999

ok, got it, readdir returns the file name, not the file path thats why the filetests always returned false.

They have: 447 posts

Joined: Oct 1999

ok, heres my final code if anyone is interested, works like a charm.

#####################################

@dirs[0] = 'c:/';

open(OUTFILE, ">data.txt");

foreach(@dirs)
{ opendir(DIR, $_);
@temp = readdir(DIR);
foreach $file(@temp)
{ $file = $_ . $file . '/';
if(-d $file && $file !~ /\.\/$/)
{ push(@dirs, $file) if -d $file;
print OUTFILE "$file\n";
}
}
close(DIR);
}

close(OUTFILE);

##########################################

thanks for all the help!

jk Sticking out tongue

They have: 122 posts

Joined: Jun 2000

I prefer the unix way, 'find / -type d > directories'.

They have: 161 posts

Joined: Dec 1999

Although File::Find would work perfectly in this case, I offer my own solution. It is a recursive approach:

code:

@dirs = ();
populate($start);

sub populate {
  my $dir = shift;
  push @dirs, $dir;
  local (*DIR,$_);
  opendir DIR, $dir or warn("can't open $dir: $!"), return;
  while (defined($_ = readdir DIR)) {
    populate("$dir/$_") if !/^\.\.?$/ and -d "$dir/$_";
  }
  closedir DIR;
}
[/code]

------------------
-- 
MIDN 4/C PINYAN, NROTCURPI, US Naval Reserve 

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.