The result of opendir is a list of files that were in the directory at the time it was called. If you change the directory, you need to call rewinddir :
my $dir_snippets = "/tmp/fruit"; system ("rm -rf $dir_snippets"); mkdir $dir_snippets or die $!; my $banana = "$dir_snippets/banana"; system ("touch $banana"); opendir(SNIPPETS, $dir_snippets);
Gives you
>>>.
>>>.
>>> ..
Without rewinddir you will get
>>>.
>>> ..
>>> banana
Just testing with C, I get the same thing:
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <dirent.h> #include <errno.h> int main () { DIR * fruit; struct dirent * file; fruit = opendir ("/tmp/fruit"); if (! fruit) { fprintf (stderr, "opendir failed: %s\n", strerror (errno)); exit (EXIT_FAILURE); } while (file = readdir (fruit)) { unlink ("/tmp/fruit/banana"); printf (">>> %s\n", file->d_name); } closedir (fruit); }
Gives the following (after creating the "banana" file with "touch"):
$ ./a.out
>>>.
>>> ..
>>> banana
$ ./a.out
>>>.
>>> ..
Snake plissken
source share