Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
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
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?
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 examining the Monastery: (14)
As of 2015-07-31 10:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (276 votes), past polls