Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: forcing list-context

by pvaldes (Chaplain)
on Jan 23, 2012 at 15:22 UTC ( [id://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 (Abbot) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://949434]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2024-04-23 10:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found