Learning Perl

Learning PerlSearch this book
Previous: 12.4 Opening and Closing a Directory HandleChapter 12
Directory Access
Next: 12.6 Exercises
 

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


Previous: 12.4 Opening and Closing a Directory HandleLearning PerlNext: 12.6 Exercises
12.4 Opening and Closing a Directory HandleBook Index12.6 Exercises