1package DirHandle; 2 3=head1 NAME 4 5DirHandle - supply object methods for directory handles 6 7=head1 SYNOPSIS 8 9 use DirHandle; 10 $d = new DirHandle "."; 11 if (defined $d) { 12 while (defined($_ = $d->read)) { something($_); } 13 $d->rewind; 14 while (defined($_ = $d->read)) { something_else($_); } 15 undef $d; 16 } 17 18=head1 DESCRIPTION 19 20The C<DirHandle> method provide an alternative interface to the 21opendir(), closedir(), readdir(), and rewinddir() functions. 22 23The only objective benefit to using C<DirHandle> is that it avoids 24namespace pollution by creating globs to hold directory handles. 25 26=cut 27 28require 5.000; 29use Carp; 30use Symbol; 31 32sub new { 33 @_ >= 1 && @_ <= 2 or croak 'usage: new DirHandle [DIRNAME]'; 34 my $class = shift; 35 my $dh = gensym; 36 if (@_) { 37 DirHandle::open($dh, $_[0]) 38 or return undef; 39 } 40 bless $dh, $class; 41} 42 43sub DESTROY { 44 my ($dh) = @_; 45 closedir($dh); 46} 47 48sub open { 49 @_ == 2 or croak 'usage: $dh->open(DIRNAME)'; 50 my ($dh, $dirname) = @_; 51 opendir($dh, $dirname); 52} 53 54sub close { 55 @_ == 1 or croak 'usage: $dh->close()'; 56 my ($dh) = @_; 57 closedir($dh); 58} 59 60sub read { 61 @_ == 1 or croak 'usage: $dh->read()'; 62 my ($dh) = @_; 63 readdir($dh); 64} 65 66sub rewind { 67 @_ == 1 or croak 'usage: $dh->rewind()'; 68 my ($dh) = @_; 69 rewinddir($dh); 70} 71 721; 73