Search code examples
perldirectoryreaddiropendir

readdir returning empty array on second call


When I open a directory with opendir() and later call readdir() two times in a row, the latter returns an empty array.


minimal_example.pl:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper qw(Dumper);

opendir(my $DIRH, "/home") or die "Cannot open /home: $!\n";

my @FILES  = readdir($DIRH);
my @FILES2 = readdir($DIRH);

print Dumper \@FILES;
print Dumper \@FILES2;

output:

$VAR1 = [
          '.',
          '..',
          'users',
          'sysadmin',
          'ne'
        ];
$VAR1 = [];

Is that expected behavior?


Solution

  • Many operators in Perl return differently based on whether they are called in list or scalar context. This is the case with readdir

    Returns the next directory entry for a directory opened by opendir. If used in list context, returns all the rest of the entries in the directory. If there are no more entries, returns the undefined value in scalar context and the empty list in list context.

    Since the return of readdir in your code is assigned to an array it is in list context so it reads all that there is in that directory. Thus, as the directory handle got to the end of the filelist, the next "read" returns an empty list (even if more files were added in the meanwhile).

    I don't see what is expected from reading a list of files twice, but to process a directory multiple times one can use rewinddir.