Why are Perl readdir () cache directory entries?

For some reason, Perl keeps caching entries in a directory that I am trying to read using readdir :

opendir(SNIPPETS, $dir_snippets); # or die... while ( my $snippet = readdir(SNIPPETS) ) { print ">>>".$snippet."\n"; } closedir(SNIPPETS); 

Since my directory contains two files test.pl and test.man, I expect the following output:

 . .. test.pl test.man 

Unfortunately, Perl returns a lot of files that have since disappeared, for example, because I tried to rename them. After moving test.pl to test.yeah, Perl will return the following list:

 . .. test.pl test.yeah test.man 

What is the reason for this strange behavior? The documentation for opendir , readdir, and closedir does not mention any caching mechanism. "ls -l" explicitly contains only two files.

+6
file perl
source share
1 answer

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); # or die... while ( my $snippet = readdir(SNIPPETS) ) { if (-f $banana) { unlink $banana; rewinddir SNIPPETS; } print ">>>".$snippet."\n"; } closedir(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 
 >>>.
 >>> ..
+9
source share

All Articles