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

Re: count file in directory

by kcott (Chancellor)
on Sep 04, 2013 at 09:35 UTC ( #1052271=note: print w/replies, xml ) Need Help??

in reply to count file in directory

G'day joaase,

Welcome to the monastery.

In addition to the two files you say you have, you've also got '.' (current directory) and '..' (parent directory). That makes four entries in total.

You can check this by printing the directory entries. Something like (code layout tidied):

.... while (my $file = readdir(DIR)) { print "$file\n"; if ($file) { ...

The readdir documentation has example code for excluding '.' and '..'.

Unrelated to your posted issue, I see another problem with:

... while (my $file = readdir(DIR)) { if ($file) { $file_count++; } } ...

"if ($file) {" will always be TRUE: you'll never get to that condition if "my $file = readdir(DIR)" is FALSE. As currently written, that test is completely redundant and should be removed (i.e. replace the whole if block with just "++$file_count;".

Perhaps you wanted a file test operator in the if condition. For instance, "if (-f $file) {" would check for plain files: '.', '..' and any other directories would not be included in the count; this would resolve your original problem.

-- Ken

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1052271]
[moritz]: and everybody is like "if you just copy 250 lines of ugly JS into your free nodelet, and happent to know about it, there is a 40% that this workaround kinda works, sometimes"
[moritz]: ... "so there is no need to do anything"
[LanX]: and the code is a bit of a mess
[LanX]: moritz, no ... jsut copy one line of my code
[moritz]: I'm still using the CB, because ambrus's #cbstream makes it bearable
[LanX]: ... the rest is loaded from a node
[holli]: the best course of action would be to transfer the data to something well tested. even if it isnt perl based
[moritz]: but even if I had all the time in the world, I wouldn't spend much on perlmonks
[LanX]: holli: LOL
[LanX]: moritz: why ? family?

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (12)
As of 2017-11-20 19:21 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (291 votes). Check out past polls.