Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2018-02-25 06:42 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (312 votes). Check out past polls.