12.5. Reading a Directory Handle

Once we have a directory handle open, we can read the list of names with readdir , which takes a single parameter: the directory handle. Each invocation of readdir in a scalar context returns the next filename (just the basename: you'll never get any slashes in the return value) in a seemingly random order.[5] If there are no more names, readdir returns undef.[6] Invoking readdir in a list context returns all of the remaining names as a list with one name per element. Here's an example of listing all of the names from the /etc directory:

opendir(ETC,"/etc") || die "no etc?: $!";
while ($name = readdir(ETC)) { # scalar context, one per loop
    print "$name\n"; # prints ., .., passwd, group, and so on
}
closedir(ETC);

[5] Specifically, this is the order in which the filenames are kept in the directory—the same unordered order you get back from the find command or ls -f under UNIX.

[6] Which means you'll have to use while (defined ($name = readdir (...)) when working under Perl's -w option.

And here's a way of getting them all in alphabetical order with the assistance of sort:

opendir(ETC,"/etc") || die "no etc?: $!";
foreach $name (sort readdir(ETC)) { # list context, sorted
    print "$name\n"; # prints ., .., passwd, group, and so on
}
closedir(ETC);

The names include files that begin with a dot. This is unlike globbing with <*>, which does not return names that begin with a dot. On the other hand, it is like the shell's echo*.

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.