Reading a Directory Handle
After 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
or backslashes in the return value) in a seemingly random
order.[82] If no more
names exist, readdir
returns
undef
. 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 your
Windows directory:
$windir = $ENV{"WINDIR"}; opendir(NT, $windir) || die "no $windir?: $!"; while ($name = readdir(NT)) { # scalar context, one per loop print "$name\n"; # prints ., .., system.ini, and so on } closedir(NT);
And here’s a way of getting them all in alphabetical order with
the assistance of sort
:
$windir = $ENV{"WINDIR"}; opendir(NT, $windir) || die "no $windir?: $!"; foreach $name (sort readdir(NT)) { # list context, sorted print "$name\n"; # prints ., .., system.ini, and so on } closedir(NT);
The names include files that begin with a dot. This method is unlike
globbing with <*>
, which does not return
names that begin with a dot. This method is a relic from Perl’s
UNIX heritage, where the standard filename expansion normally does
not include any files that begin with a dot.
In the current version of Perl for Win32, and the current version of
the standard distribution, opendir
fails on UNC
paths. You can work around ...
Get Learning Perl on Win32 Systems 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.