Learning Perl on Win32 Systems

Learning Perl on Win32 SystemsSearch this book
Previous: 12.4 Opening and Closing a Directory HandleChapter 12
Directory Access
Next: 12.6 Exercises
 

12.5 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.[5] 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:

[5] Specifically, this order is the one in which the filenames are kept in the directory - the same unordered order you get back from the dir command from the command prompt.

$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 this by mapping a drive to the UNC share before using directory handles, and then using the drive letter as the path instead of the UNC path. You can do this with the Win32::NetResource module extension (see the AddConnection function) or with the Windows NT net use command. For more information on modules and the Win32 extensions, see Appendix B, Libraries and Modules.


Previous: 12.4 Opening and Closing a Directory HandleLearning Perl on Win32 SystemsNext: 12.6 Exercises
12.4 Opening and Closing a Directory HandleBook Index12.6 Exercises