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?
CodePudding user response:
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. Once that list is exhausted that next "read" returns an empty list.
I don't see what you expect from reading a list of files twice, but to process a directory multiple times one can use rewinddir.
CodePudding user response:
Yes, this is the expected behavior. Your first call to readdir()
read the entire directory and assigned its contents to @FILES
. This left nothing for the second readdir()
to read, so it returned nothing.