I am having problems with readdir
not actually reading all the files in a given folder. I am seeing only the following three files and a folder:
main.cpp
main.hpp
imageLoader.hpp
util
whilst, if I use bash ls -lat
I get following files listed:
drwxrwxr-x 11 me me 4096 Jun 30 10:48 ..
-rw-rw-r-- 1 me me 7797 Jun 30 10:19 main.cpp
-rw-rw-r-- 1 me me 690 Jun 30 10:18 crate.hpp
-rw-rw-r-- 1 me me 2691 Jun 30 10:18 crate.cpp
drwxrwxr-x 2 me me 4096 Jun 30 00:02 util
drwxrwxr-x 3 me me 4096 Jun 29 23:37 .
-rw-rw-r-- 1 me me 2584 Jun 22 19:38 imageLoader.cpp
-rw-rw-r-- 1 me me 333 Jun 22 12:56 imageLoader.hpp
-rw-rw-r-- 1 me me 52 Jun 16 17:03 main.hpp
The code I am using is nothing too crazy (edited to keep relevant):
opendir FOLDER, $folder or die "failed to open";
FILELOOP: while (readdir FOLDER){
next if /^\.\.?$/; # I do have to manually skip these right?
print "$_\n";
}
I do not understand why when I run my program it is not showing me up-to-date contents for the folder. I have permissions to see these files, the same permissions on both those that my script is reporting and those that it is not. I have had this working, it seems I have changed something somewhere to break this.
You said you are reading directories recursively. In that case, don't use bareword filehandles: They are global variables. When your recurse into a child directory, you re-open the same dirhandle to the child dir. The readdir
exhausts this dirhandle. Back in the parent directory, the handle (which is the child dir handle) is empty, thus no further files can be read.
Solution: Use lexical filehandles:
opendir my $dir, $folder or die "Can't open $folder: $!";
while (readdir $dir) {
...;
}
While we're at it, you probably want to offload the file system traversion to File::Find
. There, you just supply a callback that handles each filename, specify a start dir, and let File::Find handle the tricky parts for you.