1package DirHandle; 2 3our $VERSION = '1.05'; 4 5=head1 NAME 6 7DirHandle - (obsolete) supply object methods for directory handles 8 9=head1 SYNOPSIS 10 11 # recommended approach since Perl 5.6: do not use DirHandle 12 if (opendir my $d, '.') { 13 while (readdir $d) { something($_); } 14 rewind $d; 15 while (readdir $d) { something_else($_); } 16 } 17 18 # how you would use this module if you were going to 19 use DirHandle; 20 if (my $d = DirHandle->new(".")) { 21 while (defined($_ = $d->read)) { something($_); } 22 $d->rewind; 23 while (defined($_ = $d->read)) { something_else($_); } 24 } 25 26=head1 DESCRIPTION 27 28B<There is no reason to use this module nowadays.> 29 30The C<DirHandle> method provide an alternative interface to the 31opendir(), closedir(), readdir(), and rewinddir() functions. 32 33Up to Perl 5.5, opendir() could not autovivify a directory handle from 34C<undef>, so using a lexical handle required using a function from L<Symbol> 35to create an anonymous glob, which took a separate step. 36C<DirHandle> encapsulates this, which allowed cleaner code than opendir(). 37Since Perl 5.6, opendir() alone has been all you need for lexical handles. 38 39=cut 40 41require 5.000; 42use Carp; 43use Symbol; 44 45sub new { 46 @_ >= 1 && @_ <= 2 or croak 'usage: DirHandle->new( [DIRNAME] )'; 47 my $class = shift; 48 my $dh = gensym; 49 if (@_) { 50 DirHandle::open($dh, $_[0]) 51 or return undef; 52 } 53 bless $dh, $class; 54} 55 56sub DESTROY { 57 my ($dh) = @_; 58 # Don't warn about already being closed as it may have been closed 59 # correctly, or maybe never opened at all. 60 local($., $@, $!, $^E, $?); 61 no warnings 'io'; 62 closedir($dh); 63} 64 65sub open { 66 @_ == 2 or croak 'usage: $dh->open(DIRNAME)'; 67 my ($dh, $dirname) = @_; 68 opendir($dh, $dirname); 69} 70 71sub close { 72 @_ == 1 or croak 'usage: $dh->close()'; 73 my ($dh) = @_; 74 closedir($dh); 75} 76 77sub read { 78 @_ == 1 or croak 'usage: $dh->read()'; 79 my ($dh) = @_; 80 readdir($dh); 81} 82 83sub rewind { 84 @_ == 1 or croak 'usage: $dh->rewind()'; 85 my ($dh) = @_; 86 rewinddir($dh); 87} 88 891; 90