Приглашаем посетить
Огарев (ogarev.lit-info.ru)

Section 8.5.  Directory Handle References

Previous
Table of Contents
Next

8.5. Directory Handle References

In the same way that we can create references to filehandles, we can create directory handle references.

opendir my $dh, '.' or die "Could not open directory: $!";

foreach my $file  ( readdir( $dh ) ) {
        print "Skipper, I found $file!\n";
        }

The directory handle reference obeys the same rules we laid out before. This only works if the scalar variable does not already have a value, and the handle automatically closes when the variable goes out of scope or we assign it a new value.

8.5.1. IO::Dir

We can use object-oriented interfaces for directory handles too. The IO::Dir module has been part of the standard Perl distribution since 5.6. It doesn't add interesting new features but wraps the Perl built-in functions.[Section 8.5.  Directory Handle References]

[Section 8.5.  Directory Handle References] For each IO::Dir method name, append "dir" and look at the documentation in perlfunc.

use IO::Dir;

my $dir_fh = IO::Dir->new( '.' ) || die "Could not open dirhandle! $!\n";

while( defined( my $file = $dir_fh->read ) ) {
        print "Skipper, I found $file!\n";
        }

We don't have to create a new directory handle if we decide we want to go through the list again (perhaps later in the program). We can rewind the directory handle to start over:

while( defined( my $file = $dir_fh->read ) ) {
        print "I found $file!\n";
        }

# time passes
$dir_fh->rewind;

while( defined( my $file = $dir_fh->read ) ) {
        print "I can still find $file!\n";
        }


Previous
Table of Contents
Next