[Chapter 12] 12.5 Reading a Directory Handle
Author: Randal Schwartz, Tom Christiansen & Larry Wall
Date: 1999-07-02T01:34:39Z

#

| Chapter 12 Directory Access |

## 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*`.

12.4 Opening and Closing a Directory Handle |  | 12.6 Exercises