Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

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)


Comment on Re: forcing list-context
Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2014-12-21 18:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (106 votes), past polls