Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Counting Directories... 1

Status
Not open for further replies.

perlone

Programmer
Joined
May 20, 2001
Messages
438
Location
US
Hi,

I need to count how many directors are in so I decided to put the following code:

$root = $ENV{'DOCUMENT_ROOT'};
$basedir = "$root/cgi-bin/users";




opendir(DIR, "$basedir");
@members = readdir(DIR);
closedir(DIR);


$count = 0;
foreach $stuff (@members) {
$count++;
}

print &quot;There are <b>$count</b> dirs inside the user dir.&quot;;


But i'm getting the value 5. I know why i'm getting it but don't know how to fix it. Inside the directory users, there are actually 3 dirs. The reason i'm getting the value 5 is because it's adding the &quot;cgi-bin/users&quot; and the other 3 dirs inside the users. But I only need to count the dirs that inside the directory &quot;users&quot;. Any ideas how to fix this?



-Aaron
 
The problem is that you are counting the '.' and '..' directory entries. You can fix it like this:
Code:
$count = 0;
foreach $stuff (@members) {
next if ($stuff eq '.' || $stuff eq '..');
$count++;
}
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Thanks, Tracy! -Aaron
 
Ignoring the '.' and '..' can be accompished by combining it with the readdir function



$root = $ENV{'DOCUMENT_ROOT'};
$basedir = &quot;$root/cgi-bin/users&quot;;


opendir(DIR,&quot;$basedir&quot;) or die &quot;ERROR\n&quot;;
@members=grep !/^\.\.*?$/,readdir DIR;
closedir(DIR);


print &quot;There are &quot;,scalar @members , &quot;directories inside the user directory&quot;;


HTH
CM
 
or you can use this RE:
Code:
/^\.{1,2}$/
TAMTOWTDI
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top