Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: forcing list-context

by pvaldes (Chaplain)
on Jan 23, 2012 at 15:22 UTC ( #949434=note: print w/replies, xml ) Need Help??

in reply to forcing list-context

I need to find the number of entries in a directory.
my $dir = '/home/itsme/some/dir'; chdir $dir; my $filenum = 0; my $dirnum = 0; my $linknum = 0; opendir my $dh, $dir or die $!; foreach(readdir $dh) { if (-f){$filenum++} elsif (-l){$linknum++} elsif (-d){$dirnum++} } print "You have $filenum files, $linknum links and $dirnum directories + in $dir\n"; closedir $dh;

*(please note that this count is not recursive)

Updated: chdir line added (random results if this line is not activated)

Replies are listed 'Best First'.
Re^2: forcing list-context
by jwkrahn (Monsignor) on Jan 24, 2012 at 00:21 UTC
    foreach(readdir $dh) { if (-f){$filenum++} elsif (-l){$linknum++} elsif (-d){$dirnum++} }

    You are not going to get an accurate total because you are counting soft links in both $filenum and $linknum.    That would be better as:

    foreach ( readdir $dh ) { lstat; if ( -f _ ) { $filenum++ } elsif ( -l _ ) { $linknum++ } elsif ( -d _ ) { $dirnum++ } }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://949434]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (12)
As of 2016-10-27 13:13 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (362 votes). Check out past polls.