Section 8.5. Directory Handle References


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.[]

] 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";         } 




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net